<?php
/**
 * 春哥团队（www.cgtblog.com） - 春哥多端多商户万能DIY商城系统
 * Copyright © 2024 春哥技术团队 保留所有权利
 * =========================================================

 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

// +----------------------------------------------------------------------
// | 自动执行  每分钟执行一次 crontab -e 加入 */1 * * * * curl https://域名/?s=/ApiAuto/index/key/配置文件中的authtoken
// +----------------------------------------------------------------------
namespace app\controller;
use app\BaseController;
use think\facade\Db;
use think\facade\Log;
class ApiAuto extends BaseController
{
    public function initialize(){

	}
	public function index(){
		$config = include(ROOT_PATH.'config.php');
		set_time_limit(0);
		ini_set('memory_limit', -1);
		if(input('param.key')!=$config['authtoken']) die('error');
		$this->perminute();
		//执行了多少次了
		$lastautotimes = cache('autotimes');
		if(!$lastautotimes) $lastautotimes = 0;
		cache('autotimes',$lastautotimes+1);

		//Log::write('perminute');
		$lastautohour = cache('autotimehour');
		if(!$lastautohour){
			$lastautohour = strtotime(date("Ymd H:00:00")); //整点执行
			cache('autotimehour',$lastautohour);
		}
		if($lastautohour <= time() - 3600){
			cache('autotimehour',time());
			$this->perhour();
			//Log::write('perhour');
		}
		$lastautoday = cache('autotimeday');
		if(!$lastautoday){
			$lastautoday = strtotime(date("Ymd 06:00:00")); //6点执行
			cache('autotimeday',$lastautoday);
		}
		if($lastautoday <= time() - 86400){
			cache('autotimeday',time());
			$this->perday();
			\think\facade\Log::write('perday');
		}

		if(getcustom('plug_yuebao')){

			//定时0点执行
			$time = (int)date("H",time());
			if($time == 0){

				//确保一天执行一次
				$yuebaotime = cache('yuebaotime');

				$n_time = strtotime(date("Y-m-d",time()));

				if(!$yuebaotime){
					cache('yuebaotime',$n_time);
				}else{
					if($yuebaotime == $n_time){
						return;
					}else{
						cache('yuebaotime',$n_time);
					}
				}

				//计算余额宝收益
				$this->yuebao();

			}
		}
        //会员未购买 过期
        if(getcustom('member_vip_edit')){
            //定时0点执行
            $time = (int)date("H",time());
            if($time == 0){
                $this->member_vip_edit();
            }
        }
        if(getcustom('business_fenxiao')){
            //店铺分销
            if(date('H:i')=='00:01'){
                $this->businessfenxiao();
            }
        }
        if(getcustom('commission_butie')){
            //分销补贴，每天0点10分执行一次
            if(date('H:i')=='00:10'){
                $this->commission_butie();
            }
        }
        if(getcustom('product_givetongzheng')){
            //通证释放，每天0点10分执行一次
            if(date('H:i')=='00:10'){
                $this->release_tongzheng();
            }
        }
        if(getcustom('yx_choujiang_manren')){
            //满人开奖活动，每分钟执行一次开奖
            $this->manren_choujiang();
        }
		die;
	}
	//每分钟执行一次
	private function perminute(){
		$time = time();
		//60分钟自动关闭订单 释放库存
		$orderlist = Db::name('shop_order')->where('status',0)->select()->toArray();
		$autocloseArr = [];
		foreach($orderlist as $order){
			if(!$autocloseArr[$order['aid']]){
				$autocloseArr[$order['aid']] = Db::name('shop_sysset')->where('aid',$order['aid'])->value('autoclose');
			}
			if($order['createtime'] + $autocloseArr[$order['aid']]*60 > time()) continue;
			$aid = $order['aid'];
			$mid = $order['mid'];
			$orderid = intval($order['id']);
			$order = Db::name('shop_order')->where('id',$orderid)->find();
			if(!$order || $order['status']!=0){
				//return $this->json(['status'=>0,'msg'=>'关闭失败,订单状态错误']);
			}else{
				//加库存
				$oglist = Db::name('shop_order_goods')->where('aid',$aid)->where('orderid',$orderid)->select()->toArray();
				foreach($oglist as $og){
					Db::name('shop_guige')->where('aid',$aid)->where('id',$og['ggid'])->update(['stock'=>Db::raw("stock+".$og['num']),'sales'=>Db::raw("IF(sales>=".$og['num'].",sales-".$og['num'].",0)")]);
					Db::name('shop_product')->where('aid',$aid)->where('id',$og['proid'])->update(['stock'=>Db::raw("stock+".$og['num']),'sales'=>Db::raw("IF(sales>=".$og['num'].",sales-".$og['num'].",0)")]);
					if(getcustom('guige_split')){
						\app\model\ShopProduct::addlinkstock($og['proid'],$og['ggid'],$og['num']);
					}
				}
				//优惠券抵扣的返还
				if($order['coupon_rid']){
					Db::name('coupon_record')->where('aid',$aid)->where('mid',$mid)->where('id','in',$order['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
				}
				if(getcustom('money_dec')){
		            //返回余额抵扣
		            if($order['dec_money']>0){
		                \app\common\Member::addmoney($aid,$mid,$order['dec_money'],t('余额').'抵扣返回，订单号: '.$order['ordernum']);
		            }
		        }
				$rs = Db::name('shop_order')->where('id',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
				Db::name('shop_order_goods')->where('orderid',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);

				if($order['platform'] == 'toutiao'){
					\app\common\Ttpay::pushorder($aid,$order['ordernum'],2);
				}
				//return $this->json(['status'=>1,'msg'=>'操作成功']);
				//$rs = \app\common\Wxpay::closeorder($order['aid'],$order['ordernum'],$order['platform']);
			}
		}
		//秒杀
		$orderlist = Db::name('seckill_order')->where('status',0)->select()->toArray();
		$autocloseArr = [];
		foreach($orderlist as $order){
			if(!$autocloseArr[$order['aid']]){
				$autocloseArr[$order['aid']] = Db::name('seckill_sysset')->where('aid',$order['aid'])->value('autoclose');
			}
			if($order['createtime'] + $autocloseArr[$order['aid']]*60 > time()) continue;
			$aid = $order['aid'];
			$mid = $order['mid'];
			$orderid = intval($order['id']);
			$order = Db::name('seckill_order')->where('id',$orderid)->find();
			if(!$order || $order['status']!=0){
				//return $this->json(['status'=>0,'msg'=>'关闭失败,订单状态错误']);
			}else{
				//加库存
				Db::name('seckill_product')->where('aid',$aid)->where('id',$order['proid'])->update(['stock'=>Db::raw("stock+".$order['num']),'sales'=>Db::raw("IF(sales>=".$order['num'].",sales-".$order['num'].",0)")]);
                if($order['ggid']) Db::name('seckill_guige')->where('aid',$aid)->where('id',$order['ggid'])->update(['stock'=>Db::raw("stock+".$order['num']),'sales'=>Db::raw("IF(sales>=".$order['num'].",sales-".$order['num'].",0)")]);
				//优惠券抵扣的返还
				if($order['coupon_rid'] > 0){
					Db::name('coupon_record')->where('aid',$aid)->where('mid',$mid)->where('id',$order['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
				}
				$rs = Db::name('seckill_order')->where('id',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
			}
		}

		//积分兑换
		$orderlist = Db::name('scoreshop_order')->where('status',0)->select()->toArray();
		$autocloseArr = [];
		foreach($orderlist as $order){
			if(!$autocloseArr[$order['aid']]){
				$autocloseArr[$order['aid']] = Db::name('scoreshop_sysset')->where('aid',$order['aid'])->value('autoclose');
			}
			if($order['createtime'] + $autocloseArr[$order['aid']]*60 > time()) continue;
			$aid = $order['aid'];
			$mid = $order['mid'];
			$orderid = intval($order['id']);
			$order = Db::name('scoreshop_order')->where('id',$orderid)->find();
			if(!$order || $order['status']!=0){
				//return $this->json(['status'=>0,'msg'=>'关闭失败,订单状态错误']);
			}else{
				//加库存
				$oglist = Db::name('scoreshop_order_goods')->where('aid',$aid)->where('orderid',$orderid)->select()->toArray();
				foreach($oglist as $og){
					Db::name('scoreshop_product')->where('aid',$aid)->where('id',$og['proid'])->update(['stock'=>Db::raw("stock+".$og['num']),'sales'=>Db::raw("IF(sales>=".$og['num'].",sales-".$og['num'].",0)")]);
                    if($og['ggid']) Db::name('scoreshop_guige')->where('aid',$aid)->where('id',$og['ggid'])->update(['stock'=>Db::raw("stock+".$og['num']),'sales'=>Db::raw("IF(sales>=".$og['num'].",sales-".$og['num'].",0)")]);
				}
				//优惠券抵扣的返还
				if($order['coupon_rid'] > 0){
					Db::name('coupon_record')->where('aid',$aid)->where('mid',$mid)->where('id',$order['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
				}
				$rs = Db::name('scoreshop_order')->where('id',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
				Db::name('scoreshop_order_goods')->where('orderid',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
			}
		}

		//预约服务
		$orderlist = Db::name('yuyue_order')->where('status',0)->select()->toArray();
		$autocloseArr = [];
		foreach($orderlist as $order){
			if(!$autocloseArr[$order['aid'].'_'.$order['bid']]){
				$autocloseArr[$order['aid'].'_'.$order['bid']] = Db::name('yuyue_set')->where('aid',$order['aid'])->where('bid',$order['bid'])->value('autoclose');
			}
			if($order['createtime'] + $autocloseArr[$order['aid'].'_'.$order['bid']]*60 > time()) continue;
			$aid = $order['aid'];
			$mid = $order['mid'];
			$orderid = intval($order['id']);

			//加库存
			Db::name('yuyue_product')->where('aid',$aid)->where('id',$order['proid'])->update(['stock'=>Db::raw("stock+".$order['num']),'sales'=>Db::raw("IF(sales>=".$order['num'].",sales-".$order['num'].",0)")]);
			Db::name('yuyue_guige')->where('aid',$aid)->where('id',$order['ggid'])->update(['stock'=>Db::raw("stock+".$order['num']),'sales'=>Db::raw("IF(sales>=".$order['num'].",sales-".$order['num'].",0)")]);
			//优惠券抵扣的返还
			if($order['coupon_rid'] > 0){
				Db::name('coupon_record')->where('aid',$aid)->where('mid',$mid)->where('id',$order['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
			}
			$rs = Db::name('yuyue_order')->where('id',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
			//积分抵扣的返还
			if($order['scoredkscore'] > 0){
				\app\common\Member::addscore($aid,$order['mid'],$order['scoredkscore'],'订单退款返还');
			}
			//退款成功通知
			$tmplcontent = [];
			$tmplcontent['first'] = '您的订单已经完成退款，¥'.$order['refund_money'].'已经退回您的付款账户，请留意查收。';
			$tmplcontent['remark'] = '请点击查看详情~';
			$tmplcontent['orderProductPrice'] = (string) $order['refund_money'];
			$tmplcontent['orderProductName'] = $order['title'];
			$tmplcontent['orderName'] = $order['ordernum'];
            $tmplcontentNew = [];
            $tmplcontentNew['character_string1'] = $order['ordernum'];//订单编号
            $tmplcontentNew['thing2'] = $order['title'];//商品名称
            $tmplcontentNew['amount3'] = $order['refund_money'];//退款金额
			\app\common\Wechat::sendtmpl(aid,$order['mid'],'tmpl_tuisuccess',$tmplcontent,m_url('pages/my/usercenter'),$tmplcontentNew);
			//订阅消息
			$tmplcontent = [];
			$tmplcontent['amount6'] = $order['refund_money'];
			$tmplcontent['thing3'] = $order['title'];
			$tmplcontent['character_string2'] = $order['ordernum'];
			
			$tmplcontentnew = [];
			$tmplcontentnew['amount3'] = $order['refund_money'];
			$tmplcontentnew['thing6'] = $order['title'];
			$tmplcontentnew['character_string4'] = $order['ordernum'];
			\app\common\Wechat::sendwxtmpl($aid,$order['mid'],'tmpl_tuisuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);

			//短信通知
			$member = Db::name('member')->where('id',$order['mid'])->find();
			if($member['tel']){
				$tel = $member['tel'];
			}else{
				$tel = $order['tel'];
			}
			$rs = \app\common\Sms::send($aid,$tel,'tmpl_tuisuccess',['ordernum'=>$order['ordernum'],'money'=>$order['refund_money']]);
		}

		//预约服务 几分钟内未接单自动退款
		if(getcustom('hmy_yuyue')){
			$orderlist = Db::name('yuyue_order')->where('status',1)->where('worker_orderid',0)->select()->toArray();
			$autocloseArr = [];
			foreach($orderlist as $order){
				if(!$autocloseArr[$order['aid'].'_'.$order['bid']]){
					$autocloseArr[$order['aid'].'_'.$order['bid']] = Db::name('yuyue_set')->where('aid',$order['aid'])->where('bid',$order['bid'])->value('minminute');
				}
				if($order['paytime'] + $autocloseArr[$order['aid'].'_'.$order['bid']]*60 > time()) continue;
				$aid = $order['aid'];
				$mid = $order['mid'];
				$bid = $order['bid'];
				$orderid = intval($order['id']);
				//	$rs = Db::name('yuyue_order')->where('id',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
				//退款
				Db::name('yuyue_order')->where('id',$orderid)->where('aid',$aid)->where('bid',$bid)->update(['status'=>4,'refund_status'=>2,'refund_money'=>$order['totalprice'],'refund_reason'=>'超时未接单退款','refund_time'=>time()]);
				$rs = \app\common\Order::refund($order,$order['totalprice'],'超时未接单退款');

				$config = include(ROOT_PATH.'config.php');
				$appId=$config['hmyyuyue']['appId'];
				$appSecret=$config['hmyyuyue']['appSecret'];
				$headrs = array('content-type: application/json;charset=UTF-8','appid:'.$appId,'appSecret:'.$appSecret);
				$url = 'https://shifu.api.kkgj123.cn/api/1/order/cancel';
				$data = [];
				$data['sysOrderNo'] = $order['sysOrderNo'];
				$data['cancelParty'] = 3;
				$data['cancelReason'] = '超时取消';
				$data = json_encode($data,JSON_UNESCAPED_UNICODE);
				$res = curl_post($url,$data,'',$headrs);
				$res = json_decode($res,true);
			}
		}
		//超时的团
		$time = time();
		$tlist = Db::name('collage_order_team')->where("`status`=1 and createtime+teamhour*3600<{$time}")->select()->toArray();
		Db::name('collage_order_team')->where("`status`=1 and createtime+teamhour*3600<{$time}")->update(['status'=>3]);//改成失败状态
		if($tlist){//退款
			foreach($tlist as $t){
				$sysset = Db::name('admin')->where('id',$t['aid'])->find();
				$orderlist = Db::name('collage_order')->where('status',1)->where('teamid',$t['id'])->where('buytype','<>',1)->select()->toArray();
				foreach($orderlist as $orderinfo){
					if($orderinfo['paytype']=='微信支付'){
						$rs = \app\common\Wxpay::refund($orderinfo['aid'],$orderinfo['platform'],$orderinfo['ordernum'],$orderinfo['totalprice'],$orderinfo['totalprice'],'拼团失败');
					}else{
						\app\common\Member::addmoney($orderinfo['aid'],$orderinfo['mid'],$orderinfo['totalprice'],'拼团失败退款');
					}
					//积分抵扣的返还
					if($orderinfo['scoredk'] > 0){
						\app\common\Member::addscore($orderinfo['aid'],$orderinfo['mid'],$orderinfo['scoredk'],'拼团失败退款返还');
					}
					//优惠券抵扣的返还
					if($orderinfo['coupon_rid'] > 0){
						Db::name('coupon_record')->where('aid',aid)->where('mid',$orderinfo['mid'])->where('id',$orderinfo['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
					}
					Db::name('collage_order')->where('id',$orderinfo['id'])->update(['status'=>4]);
					//退款成功通知
					$tmplcontent = [];
					$tmplcontent['first'] = '拼团失败退款，¥'.$orderinfo['totalprice'].'已经退回您的付款账户，请留意查收。';
					$tmplcontent['remark'] = '请点击查看详情~';
					$tmplcontent['orderProductPrice'] = (string) $orderinfo['totalprice'];
					$tmplcontent['orderProductName'] = $orderinfo['title'];
					$tmplcontent['orderName'] = $orderinfo['ordernum'];
                    $tmplcontentNew = [];
                    $tmplcontentNew['character_string1'] = $orderinfo['ordernum'];//订单编号
                    $tmplcontentNew['thing2'] = $orderinfo['title'];//商品名称
                    $tmplcontentNew['amount3'] = $orderinfo['totalprice'];//退款金额
					\app\common\Wechat::sendtmpl($orderinfo['aid'],$orderinfo['mid'],'tmpl_tuisuccess',$tmplcontent,m_url('activity/collage/orderlist',$orderinfo['aid']),$tmplcontentNew);
					//订阅消息
					$tmplcontent = [];
					$tmplcontent['amount6'] = $orderinfo['totalprice'];
					$tmplcontent['thing3'] = $orderinfo['title'];
					$tmplcontent['character_string2'] = $orderinfo['ordernum'];
					
					$tmplcontentnew = [];
					$tmplcontentnew['amount3'] = $orderinfo['totalprice'];
					$tmplcontentnew['thing6'] = $orderinfo['title'];
					$tmplcontentnew['character_string4'] = $orderinfo['ordernum'];
					\app\common\Wechat::sendwxtmpl($orderinfo['aid'],$orderinfo['mid'],'tmpl_tuisuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);

					//短信通知
					$member = Db::name('member')->where('id',$orderinfo['mid'])->find();
					if($member['tel']){
						$tel = $member['tel'];
					}else{
						$tel = $orderinfo['tel'];
					}
					$rs = \app\common\Sms::send($orderinfo['aid'],$tel,'tmpl_tuisuccess',['ordernum'=>$orderinfo['ordernum'],'money'=>$orderinfo['totalprice']]);
				}
			}
		}


		//超时的幸运拼团
		//超时的团
		$time = time();
		$tlist = Db::name('lucky_collage_order_team')->where("`status`=1 and createtime+teamhour*3600<{$time}")->select()->toArray();
		Db::name('lucky_collage_order_team')->where("`status`=1 and createtime+teamhour*3600<{$time}")->update(['status'=>3]);//改成失败状态
		if($tlist){//退款
			foreach($tlist as $t){
				$sysset = Db::name('admin')->where('id',$t['aid'])->find();
				$orderlist = Db::name('lucky_collage_order')->where('status',1)->where('isjiqiren',0)->where('teamid',$t['id'])->where('buytype','<>',1)->select()->toArray();
				foreach($orderlist as $orderinfo){
					$product = Db::name('lucky_collage_product')->where(['id'=>$orderinfo['proid']])->find();
					if($product['failtklx']=='1'){
						\app\common\Order::refund($orderinfo,$orderinfo['totalprice'],'拼团失败订单退款');
					}else{
						\app\common\Member::addmoney($orderinfo['aid'],$orderinfo['mid'],$orderinfo['totalprice'],'拼团失败退款');
					}
					/*if($orderinfo['paytype']=='微信支付'){
						$rs = \app\common\Wxpay::refund($orderinfo['aid'],$orderinfo['platform'],$orderinfo['ordernum'],$orderinfo['totalprice'],$orderinfo['totalprice'],'拼团失败');
					}else{
						\app\common\Member::addmoney($orderinfo['aid'],$orderinfo['mid'],$orderinfo['totalprice'],'拼团失败退款');
					}*/
					//积分抵扣的返还
					if($orderinfo['scoredk'] > 0){
						\app\common\Member::addscore($orderinfo['aid'],$orderinfo['mid'],$orderinfo['scoredk'],'拼团失败退款返还');
					}
					//优惠券抵扣的返还
					if($orderinfo['coupon_rid'] > 0){
						Db::name('coupon_record')->where('aid',aid)->where('mid',$orderinfo['mid'])->where('id',$orderinfo['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
					}
					Db::name('lucky_collage_order')->where('id',$orderinfo['id'])->update(['status'=>4]);
					//退款成功通知
					$tmplcontent = [];
					if($product['failtklx']=='1'){
						$tmplcontent['first'] = '拼团失败退款，¥'.$orderinfo['totalprice'].'已经退回您的付款账户，请留意查收。';
					}else{
						$tmplcontent['first'] = '拼团失败退款，¥'.$orderinfo['totalprice'].'已经退回您的余额账户，请留意查收。';
					}
					$tmplcontent['remark'] = '请点击查看详情~';
					$tmplcontent['orderProductPrice'] = (string) $orderinfo['totalprice'];
					$tmplcontent['orderProductName'] = $orderinfo['title'];
					$tmplcontent['orderName'] = $orderinfo['ordernum'];
                    $tmplcontentNew = [];
                    $tmplcontentNew['character_string1'] = $orderinfo['ordernum'];//订单编号
                    $tmplcontentNew['thing2'] = $orderinfo['title'];//商品名称
                    $tmplcontentNew['amount3'] = $orderinfo['totalprice'];//退款金额
					\app\common\Wechat::sendtmpl($orderinfo['aid'],$orderinfo['mid'],'tmpl_tuisuccess',$tmplcontent,m_url('activity/luckycollage/orderlist',$orderinfo['aid']),$tmplcontentNew);
					//订阅消息
					$tmplcontent = [];
					$tmplcontent['amount6'] = $orderinfo['totalprice'];
					$tmplcontent['thing3'] = $orderinfo['title'];
					$tmplcontent['character_string2'] = $orderinfo['ordernum'];
					
					$tmplcontentnew = [];
					$tmplcontentnew['amount3'] = $orderinfo['totalprice'];
					$tmplcontentnew['thing6'] = $orderinfo['title'];
					$tmplcontentnew['character_string4'] = $orderinfo['ordernum'];
					\app\common\Wechat::sendwxtmpl($orderinfo['aid'],$orderinfo['mid'],'tmpl_tuisuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);

					//短信通知
					$member = Db::name('member')->where('id',$orderinfo['mid'])->find();
					if($member['tel']){
						$tel = $member['tel'];
					}else{
						$tel = $order['tel'];
					}
					$rs = \app\common\Sms::send($orderinfo['aid'],$tel,'tmpl_tuisuccess',['ordernum'=>$orderinfo['ordernum'],'money'=>$orderinfo['totalprice']]);
				}
			}
		}
		
		if(getcustom('yueke')){
			$orderlist = Db::name('yueke_order')->where('status',0)->select()->toArray();
			$autocloseArr = [];
			foreach($orderlist as $order){
				if(!$autocloseArr[$order['aid']]){
					$autocloseArr[$order['aid']] = Db::name('yueke_set')->where('aid',$order['aid'])->value('autoclose');
				}
				if($order['createtime'] + $autocloseArr[$order['aid']]*60 > time()) continue;
				$aid = $order['aid'];
				$mid = $order['mid'];
				$orderid = intval($order['id']);
				$order = Db::name('yueke_order')->where('id',$orderid)->find();
				if(!$order || $order['status']!=0){
					//return $this->json(['status'=>0,'msg'=>'关闭失败,订单状态错误']);
				}else{
					//优惠券抵扣的返还
					if($order['coupon_rid'] > 0){
						Db::name('coupon_record')->where('aid',$aid)->where('mid',$mid)->where('id',$order['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
					}
					$rs = Db::name('yueke_order')->where('id',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
				}
			}
		}

        if(getcustom('express_wx')){
            //判断是否自动派单
            $peisong_set = \db('peisong_set')->where('express_wx_status',1)->where('express_wx_paidan',1)->select()->toArray();
            if($peisong_set){
                foreach ($peisong_set as $set){
                    $orderlist = Db::name('shop_order')->where('aid',$set['aid'])->where('status',1)->where('freight_type',2)->whereNull('express_type')->limit(50)->select()->toArray();
                    foreach ($orderlist as $item){
                        Db::name('shop_order')->where('id',$item['id'])->update(['express_type'=>'express_wx']);
                        \app\custom\ExpressWx::addOrder('shop_order',$item);
                    }
                }
            }
        }

		if(getcustom('plug_mantouxia')){
			Db::name('form_order')->where('money','>',0)->where('paystatus',0)->where('createtime','<',time() - 3600)->delete();
			Db::name('payorder')->where('type','form')->where('status',0)->where('createtime','<',time() - 3600)->delete();
		}

		$wxpaylog = Db::name('wxpay_log')->whereRaw('fenzhangmoney>0 or fenzhangmoney2>0')->where('isfenzhang',0)->where('createtime','<',time()-60)->select()->toArray();
		if($wxpaylog){
			$dbwxpayset = Db::name('sysset')->where('name','wxpayset')->value('value');
			$dbwxpayset = json_decode($dbwxpayset,true);

			foreach($wxpaylog as $v){
				$amount = intval($v['fenzhangmoney']*100);
				$amount2 = intval($v['fenzhangmoney2']*100);
				$sub_appid = '';
				$sub_mchid = $v['sub_mchid'];
				$appinfo = \app\common\System::appinfo($v['aid'],$v['platform']);
				if(!$sub_mchid) $sub_mchid = $appinfo['wxpay_sub_mchid'];
				if($v['bid'] > 0){
					$bset = Db::name('business_sysset')->where('aid',$v['aid'])->find();
					if($bset['wxfw_status'] == 1){
						$dbwxpayset = [
							'mchname'=>$bset['wxfw_mchname'],
							'appid'=>$bset['wxfw_appid'],
							'mchid'=>$bset['wxfw_mchid'],
							'mchkey'=>$bset['wxfw_mchkey'],
							'apiclient_cert'=>$bset['wxfw_apiclient_cert'],
							'apiclient_key'=>$bset['wxfw_apiclient_key'],
						];
						$receivers = [['type'=>'MERCHANT_ID','account'=>$dbwxpayset['mchid'],'amount'=>$amount,'description'=>$sub_mchid.'分账']];
						$addreceivers = [['type'=>'MERCHANT_ID','name'=>$dbwxpayset['mchname'],'account'=>$dbwxpayset['mchid'],'relation_type'=>'SERVICE_PROVIDER']];
					}elseif($bset['wxfw_status'] == 2){
						$receivers = [];
						$addreceivers = [];
						if($amount > 0){
							$receivers[] = ['type'=>'MERCHANT_ID','account'=>$dbwxpayset['mchid'],'amount'=>$amount,'description'=>$sub_mchid.'分账'];
							$addreceivers[] = ['type'=>'MERCHANT_ID','name'=>$dbwxpayset['mchname'],'account'=>$dbwxpayset['mchid'],'relation_type'=>'SERVICE_PROVIDER'];
						}
						if($amount2 > 0){
							$receivers[] = ['type'=>'MERCHANT_ID','account'=>$bset['wxfw2_mchid'],'amount'=>$amount2,'description'=>$sub_mchid.'分账'];
							$addreceivers[] = ['type'=>'MERCHANT_ID','name'=>$bset['wxfw2_mchname'],'account'=>$bset['wxfw2_mchid'],'relation_type'=>'PARTNER'];
						}
					}
				}else{
					$admin = Db::name('admin')->where('id',$v['aid'])->find();
					if($admin['choucheng_receivertype'] == 0){
						$receivers = [['type'=>'MERCHANT_ID','account'=>$dbwxpayset['mchid'],'amount'=>$amount,'description'=>$sub_mchid.'分账']];
						$addreceivers = [['type'=>'MERCHANT_ID','name'=>$dbwxpayset['mchname'],'account'=>$dbwxpayset['mchid'],'relation_type'=>'SERVICE_PROVIDER']];
					}elseif($admin['choucheng_receivertype'] == 1){
						$receivers = [['type'=>'MERCHANT_ID','account'=>$admin['choucheng_receivertype1_account'],'amount'=>$amount,'description'=>$sub_mchid.'分账']];
						$addreceivers = [['type'=>'MERCHANT_ID','name'=>$admin['choucheng_receivertype1_name'],'account'=>$admin['choucheng_receivertype1_account'],'relation_type'=>'PARTNER']];
					}elseif($admin['choucheng_receivertype'] == 2){
						if($admin['choucheng_receivertype2_openidtype'] == 0){
							if($admin['choucheng_receivertype2_name']){
								$receivers = [['type'=>'PERSONAL_OPENID','name'=>$admin['choucheng_receivertype2_name'],'account'=>$admin['choucheng_receivertype2_account'],'amount'=>$amount,'description'=>$sub_mchid.'分账']];
								$addreceivers = [['type'=>'PERSONAL_OPENID','name'=>$admin['choucheng_receivertype2_name'],'account'=>$admin['choucheng_receivertype2_account'],'relation_type'=>'PARTNER']];
							}else{
								$receivers = [['type'=>'PERSONAL_OPENID','account'=>$admin['choucheng_receivertype2_account'],'amount'=>$amount,'description'=>$sub_mchid.'分账']];
								$addreceivers = [['type'=>'PERSONAL_OPENID','account'=>$admin['choucheng_receivertype2_account'],'relation_type'=>'PARTNER']];
							}
						}else{
							$sub_appid = $appinfo['appid'];
							if($v['platform'] == 'wx'){
								$account = $admin['choucheng_receivertype2_accountwx'];
							}else{
								$account = $admin['choucheng_receivertype2_account'];
							}
							if($admin['choucheng_receivertype2_name']){
								$receivers = [['type'=>'PERSONAL_SUB_OPENID','name'=>$admin['choucheng_receivertype2_name'],'account'=>$account,'amount'=>$amount,'description'=>$sub_mchid.'分账']];
								$addreceivers = [['type'=>'PERSONAL_SUB_OPENID','name'=>$admin['choucheng_receivertype2_name'],'account'=>$account,'relation_type'=>'PARTNER']];
							}else{
								$receivers = [['type'=>'PERSONAL_SUB_OPENID','account'=>$account,'amount'=>$amount,'description'=>$sub_mchid.'分账']];
								$addreceivers = [['type'=>'PERSONAL_SUB_OPENID','account'=>$account,'relation_type'=>'PARTNER']];
							}
						}
					}
				}
				$rs = $this->profitsharing($receivers,$addreceivers,$sub_mchid,$dbwxpayset,$v['transaction_id'],$sub_appid,0);
				if($rs['status'] == 0){
					\think\facade\Log::write($rs);
					Db::name('wxpay_log')->where('id',$v['id'])->update(['isfenzhang'=>2,'fz_errmsg'=>$rs['msg']]);
				}else{
					Db::name('wxpay_log')->where('id',$v['id'])->update(['isfenzhang'=>1,'fz_errmsg'=>$rs['msg'],'fz_ordernum'=>$rs['ordernum']]);
				}
			}
		}

        if(getcustom('member_gongxian')){
            //贡献值过期
            $adminlist = Db::name('admin')->where('member_gongxian_status',1)->select()->toArray();
            foreach($adminlist as $admin) {
                $sysset = Db::name('admin_set')->where('aid',$admin['id'])->find();
                //每笔记录超过过期时间贡献值即过期
                $level_with_expire = Db::name('member_level')->where('aid',$admin['id'])->where('gongxian_days','>',0)->column('id,gongxian_days','id');
                $loglist = [];
                if($level_with_expire){
                    $levelids_with_expire = array_keys($level_with_expire);
                    foreach ($level_with_expire as $levelids_item){
                        $log1 = Db::name('member_gongxianlog')->alias('ml')->leftJoin('member m', 'm.id = ml.mid')
                            ->where('ml.aid',$admin['id'])->where('ml.value','>',0)->where('ml.is_expire',0)->where('m.levelid','=',$levelids_item['id'])->where("ml.createtime + '".($levelids_item['gongxian_days']*86400)."' < ".$time)
                            ->field('ml.*,m.levelid')->select()->toArray();
                        if($log1)
                            $loglist = array_merge((array)$log1, (array)$loglist);
                    }
                    $log2 = Db::name('member_gongxianlog')->alias('ml')->leftJoin('member m', 'm.id = ml.mid')
                        ->where('ml.aid',$admin['id'])->where('ml.value','>',0)->where('ml.is_expire',0)->where('m.levelid','not in',$levelids_with_expire)->where("ml.createtime + '".($sysset['gongxian_days']*86400)."' < ".$time)
                        ->field('ml.*,m.levelid')->select()->toArray();
                    if($log2)
                        $loglist = array_merge((array)$log2, (array)$loglist);
                }else{
                    $loglist = Db::name('member_gongxianlog')->alias('ml')->leftJoin('member m', 'm.id = ml.mid')
                        ->where('ml.aid',$admin['id'])->where('ml.value','>',0)->where('ml.is_expire',0)->where("ml.createtime + '".($sysset['gongxian_days']*86400)."' < ".$time)
                        ->field('ml.*,m.levelid')->select()->toArray();
                }
                if($loglist){
                    foreach ($loglist as $logitem){
                        Db::name('member_gongxianlog')->where('id',$logitem['id'])->update(['is_expire' => 1, 'expire_time' => $time]);
                        \app\common\Member::addgongxian($logitem['aid'],$logitem['mid'],$logitem['value']*-1,'过期',$logitem['channel'],$logitem['orderid']);
                    }
                }
            }
        }

		if(getcustom('member_levelup_auth')){
			$orderlist = Db::name('member_salelevel_order')->where('status',0)->select()->toArray();
			foreach($orderlist as $order){
				if($order['createtime'] + 30*60 > time()) continue;
				$aid = $order['aid'];
				$mid = $order['mid'];
				$orderid = intval($order['id']);
				$order = Db::name('member_salelevel_order')->where('id',$orderid)->find();
				if(!$order || $order['status']!=0){
					//return $this->json(['status'=>0,'msg'=>'关闭失败,订单状态错误']);
				}else{
					$rs = Db::name('member_salelevel_order')->where('id',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>-1]);
				}
			}
		}


		$this->fenhong('perminute');

		if(getcustom('restaurant')){
			\app\custom\Restaurant::auto_perminute();
		}

        if(getcustom('everyday_hongbao')) {
            if(date('G') == 8) {
                $this->hbcalculate();
            }
        }

        if(getcustom('image_search')){
            $this->product_img_baidu_sync();
        }
        if(getcustom('choujiang_time')){
            $this->run_dscj();
        }
        if(getcustom('invite_free')){
        	//结束已完成的免单未发放的订单
        	\app\custom\InviteFree::deal_finishfree();
		}
        //计次优惠券过期结算
        if(getcustom('coupon_times_expire')){
            \app\model\Counpon::couponExpire();
        }
//            $this->huidong();
        if(getcustom('yx_cashback_time')){
			\app\custom\OrderCustom::deal_autocashback();
		}

		if(getcustom('extend_tour')){
			//导游相册订单
			$admin = Db::name('admin')
	            ->where('status',1)
	            ->field('id')
	            ->select()
	            ->toArray();
	        if($admin){
	            foreach($admin as $v){
					$tour_custom  = new \app\custom\TourCustom();
		        	$deal_tpl = $tour_custom->get_updated_order($v['id']);
		        }
		        unset($v);
	        }
		}

		if(getcustom('extend_yuyue_car')){
			//预约洗车订单
//	        \app\custom\YuyueCustom::deal_order();
            \app\custom\YuyueCustom::dispatch_order();
		}

        if(getcustom('score_to_money_auto')){
            //积分每日自动转入余额,每天0点1分执行
            if(date('G')=='0'){
                $this->scoreToMoney();
            }

        }

		$this->sxpayquery();

		$this->fifaauto();
		if(getcustom('lot_cerberuse')){
            $this->cerberuseExpire();
        }

        //再次同步小程序发货
        \app\common\Order::retryUploadShipping();

		if(getcustom('commission_to_score')){
		    //佣金自动转积分，每日执行一次
		    if(date('H:i')=='00:01'){
		        $this->commission_to_score();
            }
        }
        if(date('H:i')=='00:01'){
            if(getcustom('yx_day_give')){
                $this->day_give();
            }
        }

        if(getcustom('product_handwork')){
        	//手工活
            \app\custom\HandWork::sendmoney();
        }

        //统计计算累计积分
        $this->count_totalscore();
	}
	
	private function sxpayquery(){
		$payorderList = Db::name('payorder')->where('issxpay',1)->where('status',0)->where('createtime','>',time()-10*60)->where('createtime','<',time()-2*60)->select()->toArray();
		foreach($payorderList as $payorder){
			$aid = $payorder['aid'];
			$mid = $payorder['mid'];
			$ordernum = $payorder['ordernum'];
			$rs = \app\custom\Sxpay::tradeQuery($payorder);
			\think\facade\Log::write($rs);
			if($rs['status'] == 1 && ($rs['data']['tranSts'] == 'CLOSED' || $rs['data']['tranSts'] == 'FAIL' || $rs['data']['tranSts'] == 'CANCELED')){
				Db::name('payorder')->where('id',$payorder['id'])->update(['issxpay'=>0]);
			}
			if($rs['status'] == 1 && $rs['data']['tranSts'] == 'SUCCESS'){
				$attach = explode(':',$rs['data']['extend']);
				$aid = intval($attach[0]);
				$tablename = $attach[1];
				$platform = $attach[2];
				if($platform == 'sxpaymp') $platform = 'mp';
				if($platform == 'sxpaywx') $platform = 'wx';
				if($platform == 'sxpayalipay') $platform = 'alipay';
				$transaction_id = $rs['data']['transactionId'];
				$isbusinesspay = 0;
				if($attach[4]){
					$isbusinesspay = 1;
				}
				Db::name('payorder')->where('id',$payorder['id'])->update(['platform'=>$platform,'isbusinesspay'=>$isbusinesspay]);

				if($payorder['score'] > 0){
					$rs = \app\common\Member::addscore($aid,$mid,-$payorder['score'],'支付订单，订单号：'.$ordernum);
					if($rs['status'] == 0){
						$order = $payorder;
						$order['totalprice'] = $order['money'];
						$order['paytypeid'] = 2;
						\app\common\Order::refund($order,$order['money'],'积分扣除失败退款');
						continue;
					}
				}
				$rs = \app\model\Payorder::payorder($payorder['id'],'微信支付',2,$transaction_id);
				if($rs['status']==0) continue;

				$total_fee = intval($payorder['money']*100);

				$set = Db::name('admin_set')->where('aid',$aid)->find();
				//消费送积分
				if($tablename != 'recharge' && $set['scorein_money']>0 && $set['scorein_score']>0){
					$givescore = floor($total_fee*0.01 / $set['scorein_money']) * $set['scorein_score'];
					\app\common\Member::addscore($aid,$mid,$givescore,'消费送'.t('积分'));
				}
				if(getcustom('business_moneypay')){ //多商户设置的消费送积分
					if($payorder['bid'] > 0 && $tablename != 'shop'){
						$bset = Db::name('business_sysset')->where('aid',$aid)->find();
						$givescore = floor($total_fee*0.01 / $bset['scorein_money']) * $bset['scorein_score'];
						\app\common\Member::addscore($aid,$mid,$givescore,'消费送'.t('积分'));
					}
				}
				//充值送积分
				if($tablename == 'recharge' && $set['scorecz_money']>0 && $set['scorecz_score']>0){
					$givescore = floor($total_fee*0.01 / $set['scorecz_money']) * $set['scorecz_score'];
					\app\common\Member::addscore($aid,$mid,$givescore,'充值送'.t('积分'));
				}

				if($rs['status'] == 1){
					//记录
					$data = array();
					$data['aid'] = $aid;
					$data['mid'] = $payorder['mid'];
					$data['openid'] = $rs['data']['uuid'];
					$data['tablename'] = $tablename;
					$data['givescore'] = $givescore;
					$data['ordernum'] = $rs['data']['ordNo'];
					$data['mch_id'] = $rs['data']['mno'];
					$data['transaction_id'] = $rs['data']['transactionId'];
					$data['total_fee'] = $rs['data']['oriTranAmt'];
					$data['createtime'] = time();
					Db::name('wxpay_log')->insert($data);
					\app\common\Member::uplv($aid,$mid);
				}
			}
		}
	}
	private function hbcalculate()
    {
        if(getcustom('everyday_hongbao')) {
            $date = date('Y-m-d');
            $todayStart = strtotime($date);
            $yestdayStart = $todayStart - 86400;
            $yestdayEnd = $yestdayStart + 86399;

            $yestdayDate = date('Y-m-d',$yestdayStart);

            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset) {
                $aid = $sysset['aid'];
                $hd = Db::name('hongbao_everyday')->where('aid',$aid)->find();
                if($hd['status']!=1 || $hd['num'] < 1) continue;
                if($hd['starttime'] > time() && $hd['endtime'] < time()) continue;
                $haveHongbao = Db::name('hongbao_everyday_list')->where('aid',$aid)->where('createdate','=',$date)->count();
                if($haveHongbao > 0) continue;
                //前一天业绩
                if($hd['shop_order_money_type'] == 'pay') {
                    $where[] = ['status', 'in', [1,2,3]];
                    $where[] = ['paytime', 'between', [$yestdayStart,$yestdayEnd]];
                }else if($hd['shop_order_money_type'] == 'receive') {
                    $where[] = ['status', '=', 3];
                    $where[] = ['collect_time', 'between', [$yestdayStart,$yestdayEnd]];
                } else {
                    $where[] = ['status', 'in', [1,2,3]];
                    $where[] = ['paytime', 'between', [$yestdayStart,$yestdayEnd]];
                }
                $totalOrder = Db::name('shop_order')->where('aid',$aid)->where('bid', 0)->where($where)->sum('totalprice');
                $totalOrder = round($totalOrder * $hd['hongbao_bl'] / 100,2);
                $orderBusiness = Db::name('shop_order')->where('aid',$aid)->where('bid', '>',0)->where($where)->field('id,aid,bid,totalprice')->select()->toArray();
                $business = Db::name('business')->where('aid',$aid)->column('feepercent','id');
                $totalOrderBusiness = 0;
                foreach ($orderBusiness as $item) {
                    $totalOrderBusiness += $item['totalprice'] * $business[$item['bid']] / 100;
                }
                $totalOrderBusiness = round($totalOrderBusiness * $hd['hongbao_bl_business'] / 100,2);
                //买单业绩
                $maidanOrder = Db::name('maidan_order')->where('aid',$aid)->where('createtime','between',[$yestdayStart,$yestdayEnd])->where('status',1)->select()->toArray();
                $totalMaidan = 0;
                foreach ($maidanOrder as $item) {
                    $totalMaidan += $item['paymoney'] * $business[$item['bid']] / 100;
                }
                $totalMaidan = round($totalMaidan * $hd['hongbao_bl_maidan'] / 100,2);

                $yestdayLeft = Db::name('hongbao_everyday_list')->where('aid',$aid)->where('createdate','=',$yestdayDate)->sum('left');
                $total = $totalOrder + $totalOrderBusiness + $totalMaidan + $yestdayLeft;
                //生成随机红包(改为平均)
                $dataHongbao = [];
                $time = time();
//            $total = $total * 100;
                $minMoney = 1;
                $avgMoney = $total/$hd['num'];
                $avgMoney = substr(sprintf("%.3f", $avgMoney), 0, -1);
//            dd($total);
                if($avgMoney < 0.01) continue;
                for($i=0;$i<$hd['num'];$i++) {
                    if($i == $hd['num'] - 1)
                        $money = $total;
                    else
//                    $money = rand($minMoney,($total - ($hd['num']-$i) * $minMoney));
                        $money = $avgMoney;
                    $dataHongbao[] = [
                        'aid' => $aid,
                        'createdate' => $date,
                        'createtime' => $time,
                        'money' => $money,
                        'left' => $money,
                    ];
                    $total -= $money;
                    if($total <= 0) {
                        break;
                    }
                }
                Db::name('hongbao_everyday_list')->limit(100)
                    ->insertAll($dataHongbao);
            }
        }
    }
	//每小时执行一次
	private function perhour(){
		$time = time();
		//商城自动收货
		$shopsetlist = Db::name('shop_sysset')->select()->toArray();
		foreach($shopsetlist as $sysset){
			$aid = $sysset['aid'];
			if($aid){
				if(getcustom('plug_yang')){
					$list = Db::name('shop_order')->where("aid={$aid} and bid=0 and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
				}else{
                    $owhere = [];
                    $owhere[] = ['aid','=',$aid];
                    if(getcustom('product_weight')){
                        //透支额度付款的，不自动发货
                        $owhere[] = ['paytypeid','<>',38];
                    }
					$list = Db::name('shop_order')->where($owhere)->where("status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
				}
				foreach($list as $order){
                    $refundOrder = Db::name('shop_refund_order')->where('refund_status','in',[1,4])->where('aid',$aid)->where('orderid',$order['id'])->count();
                    if($refundOrder){
                        continue;
                    }
                    //部分发货 不进行收货
                    if($order['express_isbufen'] ==1){
                        continue;
                    }
					$rs = \app\common\Order::collect($order,'shop');
					if($rs['status'] == 0) continue;
					Db::name('shop_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
					Db::name('shop_order_goods')->where('orderid',$order['id'])->update(['status'=>3,'endtime'=>time()]);
					\app\common\Member::uplv($aid,$order['mid']);
				}

				if(getcustom('plug_yang')){
					$list = Db::name('shop_order')->where("aid={$aid} and bid>0 and status=2 and ".time().">`send_time` + 3600*(select autocollecthour from ddwx_business where id=ddwx_shop_order.bid)")->select();
					foreach($list as $order){
						$refundOrder = Db::name('shop_refund_order')->where('refund_status','in',[1,4])->where('aid',$aid)->where('orderid',$order['id'])->count();
						if($refundOrder){
							continue;
						}
						$rs = \app\common\Order::collect($order,'shop');
						if($rs['status'] == 0) continue;
						Db::name('shop_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
						Db::name('shop_order_goods')->where('orderid',$order['id'])->update(['status'=>3,'endtime'=>time()]);
						\app\common\Member::uplv($aid,$order['mid']);
					}
				}
			}
		}
		//秒杀自动收货
        $seckillsetlist = Db::name('seckill_sysset')->select()->toArray();
        foreach($seckillsetlist as $sysset){
            $aid = $sysset['aid'];
            if($aid){
                $list = Db::name('seckill_order')->where("aid={$aid} and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
                foreach($list as $order){
                    $rs = \app\common\Order::collect($order,'seckill');
                    if($rs['status'] == 0) continue;
                    Db::name('seckill_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
                }
            }
        }
		//拼团自动收货
		$collagesetlist = Db::name('collage_sysset')->select()->toArray();
		foreach($collagesetlist as $sysset){
			$aid = $sysset['aid'];
			if($aid){
				$list = Db::name('collage_order')->where("aid={$aid} and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
				foreach($list as $order){
					$rs = \app\common\Order::collect($order,'collage');
					if($rs['status'] == 0) continue;
					Db::name('collage_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
				}
			}
		}
		//团购自动收货
        $tuangousetlist = Db::name('tuangou_sysset')->select()->toArray();
        foreach($tuangousetlist as $sysset){
            $aid = $sysset['aid'];
            if($aid){
                $list = Db::name('tuangou_order')->where("aid={$aid} and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
                foreach($list as $order){
                    $rs = \app\common\Order::collect($order,'tuangou');
                    if($rs['status'] == 0) continue;
                    Db::name('tuangou_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
                }
            }
        }
		//幸运拼团自动收货
		$collagesetlist = Db::name('lucky_collage_sysset')->select()->toArray();
		foreach($collagesetlist as $sysset){
			$aid = $sysset['aid'];
			if($aid){
				$list = Db::name('lucky_collage_order')->where("aid={$aid} and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
				foreach($list as $order){
					$rs = \app\common\Order::collect($order,'lucky_collage');
					if($rs['status'] == 0) continue;
					Db::name('lucky_collage_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
				}
			}
		}

		//砍价自动收货
		$kanjiasetlist = Db::name('kanjia_sysset')->select()->toArray();
		foreach($kanjiasetlist as $sysset){
			$aid = $sysset['aid'];
			if($aid){
				$list = Db::name('kanjia_order')->where("aid={$aid} and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
				foreach($list as $order){
					$orderid = $order['id'];
					$mid = $order['mid'];
					$rs = \app\common\Order::collect($order,'kanjia');
					if($rs['status'] == 0) continue;
					Db::name('kanjia_order')->where('aid',$aid)->where('mid',$mid)->where('id',$orderid)->update(['status'=>3,'collect_time'=>time()]);
				}
			}
		}
		//积分商城自动收货
		$scoreshopsetlist = Db::name('scoreshop_sysset')->select()->toArray();
		foreach($scoreshopsetlist as $sysset){
			$aid = $sysset['aid'];
			if($aid){
				$list = Db::name('scoreshop_order')->where("aid={$aid} and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
				foreach($list as $order){
                    $rs = \app\common\Order::collect($order,'scoreshop');
                    if($rs['status'] == 0) continue;
					Db::name('scoreshop_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
                    Db::name('scoreshop_order_goods')->where('orderid',$order['id'])->update(['status'=>3,'endtime'=>time()]);
				}
			}
		}

        //积分分销补发
        $commission_record_list = Db::name('member_commission_record')->alias('r')
            ->leftJoin('scoreshop_order o', "r.orderid = o.id and r.type = 'scoreshop'")
            ->leftJoin('scoreshop_order_goods og', "r.ogid = og.id")
            ->where('r.aid',$aid)->where('r.status',0)->where('o.status',3)
            ->where('og.iscommission',0)
            ->field('r.*,o.ordernum,o.title,og.iscommission')
            ->select()->toArray();
        if($commission_record_list){
            //佣金
            foreach($commission_record_list as $commission_record){
                Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                Db::name('scoreshop_order_goods')->where('id',$commission_record['ogid'])->update(['iscommission'=>1]);
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                }
            }
        }

		//等级到期自动降级
        $this->autoDownLevel();

		//延时结算分销佣金
		$syssetlist = Db::name('admin_set')->where('fxjiesuantime_delaydays','<>',0)->select()->toArray();
		foreach($syssetlist as $sysset){
			\app\common\Order::jiesuanCommission($sysset['aid'],$sysset);
		}
        //未延时未结算的补充结算
        $syssetlist = Db::name('admin_set')->where('fxjiesuantime_delaydays','=',0)->select()->toArray();
        foreach($syssetlist as $sysset){
            \app\common\Order::jiesuanCommission($sysset['aid'],$sysset);
        }

		if(getcustom('xixie')){
            \app\custom\Xixie::auto_endorder();
        }
        
		$this->fenhong('perhour');

        if(getcustom('restaurant')){
            \app\custom\Restaurant::auto_perhour();
        }

		if(getcustom('member_tag')){
			\app\model\Member::member_tag();
		}

        //可接收消息时段
        if(date('H') >= 8 && date('H') <= 20){

        }
        if(getcustom('fenhong_jiaquan_bylevel')){
            \app\common\Fenhong::JiesuanJiaquanFenhongByDay();
        }
        //过期商家
        \app\common\Business::update_expire_status();

        //积分过期
        \app\common\Member::scoreExpire();
        if(getcustom('yx_team_yeji')){
            $this->teamyejiJiangli();
        }
		//周期优惠券发放
		if(getcustom('member_levelup_givecoupon')){
			$setlist = Db::name('admin_set')->select()->toArray();
			foreach($setlist as $set){
				$aid = $set['aid'];
				//周期优惠券发放
				$list = Db::name('member_give_coupon_log')->where('aid',$aid)->where('status',0)->where('beginzstime','<=',time())->select()->toArray();
				foreach($list as $l){
					$days=0;
					if($l['cycle_type']==2) $days=7;
					if($l['cycle_type']==3) $days=30;
					for($i=1;$i<=$l['coupon_num'];$i++){
						\app\common\Coupon::send($aid,$l['mid'],$l['couponid'],false,0,$days);
					}
					Db::name('member_give_coupon_log')->where('id',$l['id'])->where('status',0)->update(['status'=>1,'zstime'=>time()]);
				}
			}
		}


    }
	//每天执行
	private function perday(){
		$this->fenhong('perday');

		if(getcustom('score_withdraw')){
            $this->scoreToWithdraw();
        }

		$this->depositOrderExpire();
		
		if(getcustom('fxjiesuantime_perweek')){
			//每周结算佣金
			$syssetlist = Db::name('admin_set')->where('fxjiesuantime_delaydays','<>',0)->select()->toArray();
			foreach($syssetlist as $sysset){
				\app\common\Order::jiesuanCommissionWeek($sysset['aid'],$sysset);
			}
		}

		if(getcustom('forcerebuy') && date('d') == '01'){
			$forcerebuyList = Db::name('forcerebuy')->where('type',1)->where('status',1)->select()->toArray();
			foreach($forcerebuyList as $forcerebuy){
				$aid = $forcerebuy['aid'];
				if($forcerebuy['daytype'] == 0){
					$starttime = strtotime(date('Y-m-01',strtotime(date('Y-m-01')) - 86400));
					$endtime = strtotime(date('Y-m-01')) - 1;
				}elseif($forcerebuy['daytype'] == 1){
					if(date('m') != '01' && date('m') != '04' && date('m') != '07' && date('m') != '10') continue;
					if(date('m') == '01'){
						$starttime = strtotime((date('Y')-1).'-09-01');
						$endtime = strtotime(date('Y-01-01')) - 1;
					}
					if(date('m') == '04'){
						$starttime = strtotime(date('Y').'-01-01');
						$endtime = strtotime(date('Y-04-01')) - 1;
					}
					if(date('m') == '07'){
						$starttime = strtotime(date('Y').'-04-01');
						$endtime = strtotime(date('Y-07-01')) - 1;
					}
					if(date('m') == '10'){
						$starttime = strtotime(date('Y').'-07-01');
						$endtime = strtotime(date('Y-10-01')) - 1;
					}
				}elseif($forcerebuy['daytype'] == 2){
					if(date('m') != '01') continue;
					$starttime = strtotime((date('Y')-1).'-01-01');
					$endtime = strtotime(date('Y-01-01')) - 1;
				}
				//本周期复购是否达标
				$mwhere = [];
				$mwhere[] = ['aid','=',$aid];
				if($forcerebuy['wfgtype'] == 0){
					$mwhere[] = ['commission_isfreeze','=',0];
				}
				$gettj = explode(',',$forcerebuy['gettj']);
				if(!in_array('-1',$gettj)){
					$mwhere[] = ['levelid','in',$gettj];
				}
				$memberList = Db::name('member')->where($mwhere)->select()->toArray();
				foreach($memberList as $member){
					$mid = $member['id'];
					$orderwhere = [];
					$orderwhere[] = ['aid','=',$aid];
					$orderwhere[] = ['mid','=',$mid];
					$orderwhere[] = ['createtime','>=',$starttime];
					$orderwhere[] = ['createtime','<=',$endtime];
					$orderwhere[] = ['status','in','1,2,3'];
					if($forcerebuy['fwtype'] == 1){
						$orderwhere[] = ['cid','in',$forcerebuy['categoryids']];
					}elseif($forcerebuy['fwtype'] == 2){
						$orderwhere[] = ['proid','in',$forcerebuy['productids']];
					}
					$totalprice = Db::name('shop_order_goods')->where($orderwhere)->sum('totalprice');
					if($totalprice < $forcerebuy['price']){
						if($forcerebuy['wfgtype'] == 0){
							Db::name('member')->where('id', $mid)->update(['commission_isfreeze' => 1]);
						}else{
							Db::name('member')->where('id', $mid)->update(['levelid' => $forcerebuy['wfglvid'], 'levelendtime' => 0]);
						}
					}
				}
			}
		}

        if(getcustom('coupon_expire_notice')){
            \app\common\Coupon::auto_expire_notice();
        }
        if(getcustom('region_partner')){
            //每天发放区域分红
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset){
                \app\common\Fenhong::regionPartnerBonus($sysset['aid'],$sysset);
            }
        }
        if(getcustom('coupon_xianxia_buy')){
            $this->xianixaCouponYeji(); 
        }
        //平台加权奖励【每月1号发放】
        if(getcustom('commission_platform_avg_bonus')){
            $this->platformAvgBonus();
        }
        //薪资奖励【每月1号发放】
        if(getcustom('member_level_salary_bonus')){
            $this->levelSalaryBonus();
        }
	}
	//普通客户被设置成vip后，当天必须下单，不下单，第二天自动变成普通用户，下单后，后面15天没订单也变成普通用户
    public function member_vip_edit(){
        if(getcustom('member_vip_edit')) {
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach ($syssetlist as $key => $sysset) {
                //查找刚 昨天 从普通会员升级为会员的 
                $defaultlevel = Db::name('member_level')->where('aid', $sysset['aid'])->where('isdefault', 1)->find();
                $zt_start_time = strtotime(date('Y-m-d 00:00:00', strtotime('-1 day')));
                $zt_end_time = strtotime(date('Y-m-d 23:59:59', strtotime('-1 day')));
                if ($sysset['member_no_order_expire_status']) {
                    $uplvlist = Db::name('member_levelup_order')->alias('ml')
                        ->join('member m', 'm.id = ml.mid')
                        ->where('ml.beforelevelid', $defaultlevel['id'])
                        ->where('ml.status', 2)
                        ->where('ml.levelup_time', 'between', [$zt_start_time, $zt_end_time])
                        ->where('m.levelid', '<>', $defaultlevel['id'])
                        ->where('ml.aid', $sysset['aid'])
                        ->select()->toArray();
                    foreach ($uplvlist as $key => $val) {
                        $count = Db::name('shop_order')->where('aid', $sysset['aid'])->where('mid', $val['mid'])->where('status', 'in', [1, 2, 3])
                            ->where('paytime', 'between', [$zt_start_time, $zt_end_time])->count();
                        //数量是0的 回退到普通会员
                        if ($count <= 0) {
                            Db::name('member')->where('aid', $sysset['aid'])->where('id', $val['mid'])->update(['levelid' => $defaultlevel['id'], 'levelendtime' => 0]);
                        }
                    }
                }

                //查找  15天以前升级为会员的普通会员 就是 第16天（今天执行不算 算昨天的第15天）
                $days = $sysset['member_vip_no_order_days'];
                $days_15 = $days + 1;
                $zt_start_time_15 = strtotime(date('Y-m-d 00:00:00', strtotime('-' . $days_15 . ' day')));//（昨天的）15天前的一天  24号执行 23号算16天 就是8号
                $zt_end_time_15 = strtotime(date('Y-m-d 23:59:59', strtotime('-' . $days_15 . ' day')));  //（昨天的）15天前的一天
                $uplvlist_15 = Db::name('member_levelup_order')->alias('ml')
                    ->join('member m', 'm.id = ml.mid')
                    ->where('ml.beforelevelid', $defaultlevel['id'])
                    ->where('ml.status', 2)
                    ->where('ml.levelup_time', 'between', [$zt_start_time_15, $zt_end_time_15])
                    ->where('m.levelid', '<>', $defaultlevel['id'])
                    ->field('ml.id,ml.mid,ml.status,ml.levelup_time,ml.levelid')
                    ->where('ml.aid', $sysset['aid'])
                    ->select()->toArray();

                $_after_15 = strtotime(date('Y-m-d 00:00:00', strtotime('-' . $days . ' day')));//订单是 后面15天 24号执行 23号算15天 就是9号 到昨天结束的订单数量
                foreach ($uplvlist_15 as $key => $val15) {
                    $count = Db::name('shop_order')->where('aid', $sysset['aid'])->where('mid', $val15['mid'])->where('status', 'in', [1, 2, 3])
                        ->where('paytime', 'between', [$_after_15, $zt_end_time])->count();
                    //数量是0的 回退到普通会员
                    if ($count <= 0) {
                        Db::name('member')->where('aid', $sysset['aid'])->where('id', $val15['mid'])->update(['levelid' => $defaultlevel['id'], 'levelendtime' => 0]);
                    }
                }
            }
        }
    }
	public function test(){
        Db::startTrans();
        $this->manren_choujiang();

        Db::commit();
        die('stop');
        //$this->fenhong('perhour');
        Db::startTrans();
        \app\common\Fenhong::jiesuan(1,0,0);
        die('stop');
        Db::commit();
        //$this->cerberuseExpire();
        //\app\custom\YuyueCustom::dispatch_order();
//        $this->levelSalaryBonus(1);
//        $this->platformAvgBonus(1);
//        echo 'done.....';
	}

	//分红
	private function fenhong($pertime){
		$midCommissionList = [];
		$syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
		foreach($syssetlist as $sysset){
			$aid = $sysset['aid'];
			$fhjiesuantype = $sysset['fhjiesuantype'];
            $fhjiesuantime_type = $sysset['fhjiesuantime_type'];//分红结算时间类型 0收货后，1付款后
			$fhjiesuantime = $sysset['fhjiesuantime'];
			if($fhjiesuantime_type == 1) {
                if($pertime == 'perday') continue;
                if($pertime == 'perhour') continue;
                $starttime = 1;
                $endtime = time();
            } else {
				if($fhjiesuantime == 10) continue;  //手动结算
                if($fhjiesuantime == 0){ //按天结算
                    if($pertime == 'perhour') continue;
                    if($pertime == 'perminute') continue;
                    //$starttime = strtotime(date('Y-m-d'))-86400;
					$starttime = 1;
                    $endtime = strtotime(date('Y-m-d'));
                }elseif($fhjiesuantime == 1){ //月初结算
                    if($pertime == 'perhour') continue;
                    if($pertime == 'perminute') continue;
                    //$starttime = strtotime(date('Y-m-01').' -1 month');
					$starttime = 1;
                    $endtime = strtotime(date('Y-m-01'));
                }elseif($fhjiesuantime == 2){ //按小时结算
                    if($pertime == 'perday') continue;
                    if($pertime == 'perminute') continue;
                    $starttime = 1;
                    $endtime = time();
                }elseif($fhjiesuantime == 3){ //每分钟结算
                    if($pertime == 'perday') continue;
                    if($pertime == 'perhour') continue;
                    $starttime = 1;
                    $endtime = time();
                }elseif($fhjiesuantime == 4){ //月底结算
                    if($pertime == 'perhour') continue;
                    if($pertime == 'perminute') continue;
                    if(date("t") != date("j")) continue;
                    $starttime = 1;
                    $endtime = time();
                }elseif($fhjiesuantime == 5){ //年底结算
                    if($pertime == 'perhour') continue;
                    if($pertime == 'perminute') continue;
                    if(date("t") != date("j") || date("m")!=12) continue;
                    $starttime = 1;
                    $endtime = time();
                }
            }
			\app\common\Fenhong::jiesuan($aid,$starttime,$endtime);
		}
	}
	//分账
	private function profitsharing($receivers,$addreceivers,$sub_mchid,$dbwxpayset,$transaction_id,$sub_appid,$times=0){

		$mchkey = $dbwxpayset['mchkey'];
		$sslcert = ROOT_PATH.str_replace(PRE_URL.'/','',$dbwxpayset['apiclient_cert']);
		$sslkey = ROOT_PATH.str_replace(PRE_URL.'/','',$dbwxpayset['apiclient_key']);

		$pars = array();
		$pars['mch_id'] = $dbwxpayset['mchid'];
		$pars['sub_mch_id'] = $sub_mchid;
		$pars['appid'] = $dbwxpayset['appid'];
		$pars['nonce_str'] = random(32);
		$pars['transaction_id'] = $transaction_id;
		$pars['out_order_no'] = 'P'.date('YmdHis').rand(1000,9999);
		$pars['receivers'] = jsonEncode($receivers);
		if($sub_appid){
			$pars['sub_appid'] = $sub_appid;
		}
		//$pars['sign_type'] = 'MD5';
		ksort($pars, SORT_STRING);
		$string1 = '';
		foreach ($pars as $k => $v) {
			$string1 .= "{$k}={$v}&";
		}
		$string1 .= "key=" . $mchkey;
		//$pars['sign'] = strtoupper(md5($string1));
		$pars['sign'] = strtoupper(hash_hmac("sha256",$string1 ,$mchkey));
		$xml = array2xml($pars);
		Log::write($pars);
		Log::write($xml);
		//Log::write($sslcert);
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, "https://api.mch.weixin.qq.com/secapi/pay/profitsharing" );
		curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
		curl_setopt ( $ch, CURLOPT_SSLCERT,$sslcert);
		curl_setopt ( $ch, CURLOPT_SSLKEY,$sslkey);
		curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
		curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $xml );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );

		$info = curl_exec ( $ch );
		curl_close ( $ch );
		//Log::write($info);
		$resp = (array)(simplexml_load_string($info,'SimpleXMLElement', LIBXML_NOCDATA));
		//Log::write($resp);
		if($resp['return_code'] == 'SUCCESS' && $resp['result_code']=='SUCCESS'){
			return ['status'=>1,'msg'=>'分账成功','resp'=>$resp,'ordernum'=>$pars['out_order_no']];
		}else{
			//Log::write('profitsharing');
			//Log::write($resp);
			if($times == 0 && ($resp['err_code'] == 'PARAM_ERROR' || $resp['err_code'] == 'RECEIVER_INVALID')){
			//if($times == 0 && $resp['err_code'] == 'RECEIVER_INVALID'){
				foreach($addreceivers as $addreceiver){
					$pars = array();
					$pars['mch_id'] = $dbwxpayset['mchid'];
					$pars['sub_mch_id'] = $sub_mchid;
					$pars['appid'] = $dbwxpayset['appid'];
					$pars['nonce_str'] = random(32);
					$pars['receiver'] = jsonEncode($addreceiver);
					if($sub_appid){
						$pars['sub_appid'] = $sub_appid;
					}
					//$pars['sign_type'] = 'MD5';
					ksort($pars, SORT_STRING);
					$string1 = '';
					foreach ($pars as $k => $v) {
						$string1 .= "{$k}={$v}&";
					}
					$string1 .= "key=" . $mchkey;
					//$pars['sign'] = strtoupper(md5($string1));
					$pars['sign'] = strtoupper(hash_hmac("sha256",$string1 ,$mchkey));
					$xml = array2xml($pars);
					$ch = curl_init ();
					curl_setopt ( $ch, CURLOPT_URL, "https://api.mch.weixin.qq.com/secapi/pay/profitsharingaddreceiver" );
					curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
					curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
					curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
					curl_setopt ( $ch, CURLOPT_SSLCERT,$sslcert);
					curl_setopt ( $ch, CURLOPT_SSLKEY,$sslkey);
					curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
					curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
					curl_setopt ( $ch, CURLOPT_POSTFIELDS, $xml );
					curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
					$info = curl_exec ( $ch );
					curl_close ( $ch );
					Log::write('profitsharingaddreceiver');
					Log::write($info);
					sleep(2);
				}
				return $this->profitsharing($receivers,$addreceivers,$sub_mchid,$dbwxpayset,$transaction_id,$sub_appid,1);
			}
			$msg = '未知错误';
			if ($resp['return_code'] == 'FAIL') {
				$msg = $resp['return_msg'];
			}
			if ($resp['result_code'] == 'FAIL') {
				$msg = $resp['err_code_des'];
			}
			return ['status'=>0,'msg'=>$msg,'resp'=>$resp];
		}
	}

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 1、小于1积分时，按1积分允许释放。
     * 2、大于1积分时，对小数位四舍五入取整数。
     */
	public function scoreToWithdraw()
    {
        if(getcustom('score_withdraw')){
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset){
                if($sysset['score_withdraw'] == 1 && $sysset['score_withdraw_percent_day'] > 0) {
//                $oneStand = (100 / $sysset['score_withdraw_percent_day']);
                    $oneStand = 0;
                    $mlist = Db::name('member')->where('aid', $sysset['aid'])->where('score', '>', $oneStand)->select()->toArray();
                    if($mlist) {
                        foreach ($mlist as $member) {
                            $score_withdraw = 0;
                            $score_withdraw = round($member['score'] * $sysset['score_withdraw_percent_day'] / 100);
                            if($score_withdraw < 1 && $member['score'] > 1) {
                                $score_withdraw = 1;
                            }
                            if($score_withdraw > 0) {
                                \app\common\Member::addscore($sysset['aid'],$member['id'], $score_withdraw * -1, '转为允提'.t('积分',$sysset['aid']));
                                \app\common\Member::addscore_withdraw($sysset['aid'],$member['id'], $score_withdraw, '转入允提'.t('积分',$sysset['aid']));
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 积分自动转余额
     * 1、小于1积分时，按1积分允许释放。
     * 2、大于1积分时，对小数位四舍五入取整数。
     */
    public function scoreToMoney()
    {
        if(getcustom('score_to_money_auto')){
            //判断今日是否已执行
            $exit = Db::name('score_tomoney_log')->where('w_day',date('Ymd'))->find();
            if($exit){
                return true;
            }
            //添加自动转余额记录，防止重复执行
            Db::name('score_tomoney_log')->insert(['w_day'=>date('Ymd')]);
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset){
                if($sysset['score_to_money_auto'] == 1 && $sysset['score_to_money_auto_day'] > 0) {
                    $mlist = Db::name('member')->where('aid', $sysset['aid'])->where('score', '>', 0)->select()->toArray();
                    if($mlist) {
                        foreach ($mlist as $member) {
                            $score_num = round($member['score'] * $sysset['score_to_money_auto_day'] / 100);
                            if($score_num < 1 && $member['score'] > 1) {
                                $score_num = 1;
                            }
                            $score_to_money_auto_percent = $sysset['score_to_money_auto_percent']?:1;
                            $money = bcmul($score_num,$score_to_money_auto_percent,2);
                            if($score_num > 0) {
                                \app\common\Member::addscore($sysset['aid'],$member['id'], $score_num * -1, '转入'.t('余额',$sysset['aid']));
                                \app\common\Member::addmoney($sysset['aid'],$member['id'], $money, t('积分',$sysset['aid']).'转入');
                            }
                        }
                    }
                }
            }

        }
    }

    private function yuebao()
    {
      if(getcustom('plug_yuebao')){
        //余额宝
          //读取配置
          $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
          if($syssetlist){
              foreach($syssetlist as $sv){
                  //读取大于0的用户余额
                  $sel_member = Db::name('member')
                      ->where('aid',$sv['aid'])
                      ->where('money','<>',0)
                      ->field('id,money,yuebao_rate')
                      ->select()
                      ->toArray();
                  //如果余额宝开启、余额收益比例大于0、且用户存在
                  if($sv['open_yuebao'] ==1 && $sv['yuebao_rate'] >0 && $sel_member){

                      foreach($sel_member as $mv){
                          //查询是收益率是否单独设置
                          if($mv['yuebao_rate']>=0){
                              $yuebao_rate = $mv['yuebao_rate']/100;
                          }else{
                              $yuebao_rate = $sv['yuebao_rate']/100;
                          }

                          //计算用户收益
                          $m_money = $mv['money']*$yuebao_rate;
                          if($m_money!=0){
                              $m_money = round($m_money,3);
                              \app\common\Member::addyuebaomoney($sv['aid'],$mv['id'],$m_money,t('余额宝').'收益',1);
                          }
                      }
                  }
              }
          }
      }
    }

    //寄存订单过期
    private function depositOrderExpire()
    {
        $syssetlist = Db::name('restaurant_deposit_sysset')->where('1=1')->select()->toArray();
        if($syssetlist) {
            $time = time();
            foreach ($syssetlist as $set) {
                if($set['time'] > 0) {
                    Db::name('restaurant_deposit_order')->where('aid',$set['aid'])->where('bid',$set['bid'])
                        ->where('status',1)->where('createtime','<',$time-intval($set['time'])*86400)->update(['status' => 4]);
                }
            }
        }
    }

    public function product_img_baidu_sync()
    {
        if(getcustom('image_search')){
            $limit = 10;
            $aids = Db::name('admin')->where('image_search',1)->where('status',1)->column('id');
            if(empty($aids)) return;
            $syssetlist = Db::name('baidu_set')->whereIn('aid',$aids)->where('image_search',1)->where('baidu_apikey','<>','')->where('baidu_secretkey','<>','')->select()->toArray();
            foreach($syssetlist as $sysset) {
                $aid = $sysset['aid'];
                $baidu = new \app\custom\Baidu($aid,$sysset['baidu_appid'],$sysset['baidu_apikey'],$sysset['baidu_secretkey'],$sysset['image_search_num']);
                $baidu->sync($limit);
            }
        }
    }

	public function fifaauto(){
		if(time() > 1671422400) return;

		$fifaauto_randnum = cache('fifaauto_randnum');
		if(!$fifaauto_randnum){
			$fifaauto_randnum = ''.rand(0,4);
			cache('fifaauto_randnum',$fifaauto_randnum);
		}

		if(!in_array(date('i'),['0'.$fifaauto_randnum,'1'.$fifaauto_randnum,'2'.$fifaauto_randnum,'3'.$fifaauto_randnum,'4'.$fifaauto_randnum,'5'.$fifaauto_randnum])) return;

		sleep(rand(0,20));
		
		\think\facade\Log::write('---fifaauto----'.date('Y-m-d H:i:s'));

		\app\custom\Fifa::initdata();

		$fifadata = Db::name('fifa')->where('matchStatus',2)->select()->toArray();
		foreach($fifadata as $fifa){
			$leftTeam_score = intval($fifa['leftTeam_score']);
			$rightTeam_score = intval($fifa['rightTeam_score']);
			$successguess2 = $leftTeam_score.':'.$rightTeam_score;
			if($leftTeam_score > $rightTeam_score){
				$successguess1 = '1';
				if($leftTeam_score > 5) $successguess2 = '胜其他';
			}elseif($leftTeam_score == $rightTeam_score){
				$successguess1 = '2';
				if($leftTeam_score > 3) $successguess2 = '平其他';
			}else{
				$successguess1 = '3';
				if($rightTeam_score > 5) $successguess2 = '其他';
			}
			$syssetlist = Db::name('fifa_set')->where('status',1)->select()->toArray();
            foreach($syssetlist as $sysset) {
				$aid = $sysset['aid'];
				$recordList = Db::name('fifa_record')->where('aid',$aid)->where('hid',$fifa['id'])->where('status',0)->select()->toArray();
				foreach($recordList as $record){
					$update = [];
					$update['status'] = 1;
					if($record['guess1'] && $record['guess1'] == $successguess1){
						$update['guess1st'] = 1;
						$update['givescore1'] = intval($sysset['givescore1']);
						
						$successnum = 1 + Db::name('fifa_record')->where('aid',$aid)->where('mid',$record['mid'])->whereRaw('guess1st=1')->count();
						$guess1set = json_decode($sysset['guess1set'],true);
						if($guess1set){
							foreach($guess1set as $k=>$v){
								if($v['score']!=='' && $v['score']!==null && $successnum == $v['times']){
									$update['givescore1'] += intval($v['score']);
								}
								//赠送优惠券
								if($v['coupon_id']!=='' && $v['coupon_id']!==null && $successnum == $v['times']){
									\app\common\Coupon::send($aid,$record['mid'],$v['coupon_id']);
								}
							}
						}
						\app\common\Member::addscore($aid,$record['mid'],$update['givescore1'],'世界杯竞猜成功奖励');

					}else{
						$update['guess1st'] = 2;
					}
					if($record['guess2'] && $record['guess2'] == $successguess2){
						$update['guess2st'] = 1;
						$update['givescore2'] = intval($sysset['givescore2']);
						
						$successnum = 1 + Db::name('fifa_record')->where('aid',$aid)->where('mid',$record['mid'])->whereRaw('guess2st=1')->count();
						$guess2set = json_decode($sysset['guess2set'],true);
						if($guess2set){
							foreach($guess2set as $k=>$v){
								if($v['score']!=='' && $v['score']!==null && $successnum == $v['times']){
									$update['givescore2'] += intval($v['score']);
								}
								//赠送优惠券
								if($v['coupon_id']!=='' && $v['coupon_id']!==null && $successnum == $v['times']){
									\app\common\Coupon::send($aid,$record['mid'],$v['coupon_id']);
								}
							}
						}
						\app\common\Member::addscore($aid,$record['mid'],$update['givescore2'],'世界杯竞猜成功奖励');
					}else{
						$update['guess2st'] = 2;
					}

					Db::name('fifa_record')->where('id',$record['id'])->update($update);
				}
			}
		}
	}

    //定时抽奖 1分钟执行一次
    public function run_dscj()
    {
        if (getcustom('choujiang_time')) {
            \app\model\Dscj::kaijiang();
        }
    }

    public function huidong()
    {
        \app\custom\HuiDong::syncMember();
    }

    /**
     * 自动降级
     */
    public function autoDownLevel(){

        //会员等级到期
//        $check_time = time()+35*86400;
        $check_time = time();
        $memberlist = Db::name('member')->where("levelendtime>0 and levelendtime<".$check_time)->select()->toArray();
        //dump($memberlist);
        foreach($memberlist as $member){

            if(getcustom('level_auto_down')){
                //检测推荐人和团队业绩
                $level_data = Db::name('member_level')->where('id',$member['levelid'])->find();
                if($level_data['check_type']>0){
                    $check_result = \app\common\Member::checkDownLevelCon($member,$level_data);
                    //dump($check_result);
                    if(!$check_result['is_down']){
                        //考核通过，更新有效期
                        $data_u = [];
                        if($level_data['check_type']==1){
                            $data_u['levelstarttime'] = $member['levelendtime'];
                            if($level_data['yxqdate']>0){
                                $data_u['levelendtime'] = $member['levelendtime']+86400 * $level_data['yxqdate'];
                            }else{
                                $data_u['levelendtime'] = 0;
                            }
                        }else{
                            $data_u['levelendtime'] = 0;
                        }
                        Db::name('member')->where('id', $member['id'])->update($data_u);
                        continue;
                    }
                }
            }
            $is_default = 1;
            $defaultlevel = Db::name('member_level')->where('aid', $member['aid'])->where('isdefault', 1)->find();
            if(getcustom('next_level_set') || getcustom('level_auto_down')){
                //是不是有设置的下个等级
                $curlevel = Db::name('member_level')->where('aid',$member['aid'])->where('id',$member['levelid'])->find();
                if ($curlevel && $curlevel['next_level_id'] > 0 && $curlevel['next_level_id']!=$defaultlevel['id']) {
                    $nextlevel = Db::name('member_level')->where('id',$curlevel['next_level_id'])->find();
                    if($nextlevel){
                        $is_default = 0;
                        $newlv['levelid'] = $nextlevel['id'];
                        $newlv['levelendtime'] = strtotime(date('Y-m-d')) + 86400 + 86400 * $nextlevel['yxqdate'];
                        Db::name('member')->where('id', $member['id'])->update($newlv);
                    }
                }
            }

            if($is_default==1) {
                $newlv['levelid'] = $defaultlevel['id'];
                Db::name('member')->where('id', $member['id'])->update(['levelid' => $defaultlevel['id'], 'levelendtime' => 0]);
            }
            if(getcustom('level_auto_down')) {
                //降级记录
                $order = [
                    'aid' => $member['aid'],
                    'mid' => $member['id'],
                    'from_mid' => $member['id'],
                    'pid'=>$member['pid'],
                    'levelid' => $newlv['levelid'],
                    'title' => '自动降级',
                    'totalprice' => 0,
                    'createtime' => time(),
                    'levelup_time' => time(),
                    'beforelevelid' => $member['levelid'],
                    'form0' => '类型^_^' . $check_result['desc']??'自动降级',
                    'platform' => '',
                    'status' => 2,
                    'check_down' => 1,
                ];
                Db::name('member_levelup_order')->insert($order);
            }
        }

        //其他分组等级到期后失效
        Db::name('member_level_record')->where("levelendtime>0 and levelendtime<".time())->delete();

    }
    
    //智能开门设备过期和 10分钟提醒
    public function cerberuseExpire(){
        if (getcustom('lot_cerberuse')){
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset) {
                $cerberuse_set = Db::name('cerberuse_set')->where('aid',$sysset['aid'])->find();
                //已支付的过期关闭
                Db::name('cerberuse_order')->where('aid',$sysset['aid'])->where('endtime','<=',time())->where('status','in',[1,2])->update(['status'=>3]);
                
                //未支付的 过期关闭
                $autoclose =  $cerberuse_set['autoclose']?$cerberuse_set['autoclose']:10;
                $expirse_time = time()- $autoclose * 60;
                Db::name('cerberuse_order')->where('aid',$sysset['aid'])->where('createtime','<=',$expirse_time)->where('status',0)->update(['status' => 4]);
                
                //查询距离结束还有10分钟结束的 进行提醒
                $minute = $cerberuse_set['remind_minute'];
                $remind_minute = $minute?$minute:10;
                $entime = time() + $remind_minute*60;
                $list = Db::name('cerberuse_order')->where('aid',$sysset['aid'])->where('endtime','<=',$entime)->where('status',2)->where('is_notice',0)->select()->toArray();
                if(!$list){
                    continue;
                }
                foreach($list as $key=>$val){
                    $cerberuse = Db::name('cerberuse')->where('aid',$val['aid'])->where('id',$val['proid'])->find();
                    $content =[
                        'method' => 'playTts',
                        'content' => '温馨提醒！您消费的时间还有'.$remind_minute.'分钟！即将到期！',
                        'vol' => 4
                    ];
                    $content_json = json_encode($content,JSON_UNESCAPED_UNICODE);
                    $topic= $val['aid'].'/'.$cerberuse['imei'];
                    $mqtt = new \app\custom\Mqtt();
                    $mqtt -> publish($topic,$content_json);
                    Db::name('cerberuse_order')->where('id',$val['id'])->update(['is_notice' => 1 ]);
                    //短信通知
                    $member = Db::name('member')->where('id',$val['mid'])->find();
                    if($member['tel']){
                        $tel = $member['tel'];
                    }else{
                        $tel = $val['tel'];
                    }
                    $rs = \app\common\Sms::send($val['aid'],$tel,'tmpl_use_expire',[]);
                    //模板小时到期通知
                    $wx_tmplset = Db::name('wx_tmplset')->where('aid',aid)->field('tmpl_use_expire')->find();
                    if($wx_tmplset && $wx_tmplset['tmpl_use_expire']){
                        $tmplcontent = [];
                        $tmplcontent['thing1']  = $cerberuse['title'];
                        $tmplcontent['time2'] = date('Y-m-d H:i',$val['endtime']);
                        $tmplcontent['thing3'] = '您消费的时间即将到期';
                        \app\common\Wechat::sendwxtmpl($val['aid'],$val['mid'],'tmpl_use_expire',$tmplcontent,m_url('pagesZ/cerberuse/index'),0);
                    }
                    
                }
                
            }
        }
    }

    //统计商户销量
    public function countSales(){
        ini_set('memory_limit','1024M');
        set_time_limit(0);
        $sales_type = [
            'sales' => 'sales',
            'shop' => 'shop_sales',
            'collage' => 'collage_sales',
            'kanjia' => 'kanjia_sales',
            'seckill' => 'seckill_sales',
            'tuangou' => 'tuangou_sales',
            'scoreshop' => 'scoreshop_sales',
            'lucky_collage' => 'lucky_collage_sales',
            'yuyue' => 'yuyue_sales',//预约服务
            'kecheng' => 'kecheng_sales',//课程
            'cycle' => 'cycle_sales',//周期购
            'restaurant_takeaway' => 'restaurant_takeaway_sales',//餐饮外卖
            'restaurant_shop' => 'restaurant_shop_sales'//餐饮点餐
        ];
        Db::startTrans();
        Db::execute('truncate table ddwx_business_sales');
        foreach($sales_type as $type=>$sales_field){
            switch ($type){
                case 'shop':
                    $orders = Db::name('shop_order_goods')->whereIn('status',[1,2,3])->field('aid,bid,num')->select()->toArray();
                    $products = Db::name('shop_product')->where('1=1')->field('aid,bid,sales')->select()->toArray();
                    break;
                case 'collage':
                    $orders = Db::name('collage_order')->whereIn('status',[1,2,3])->field('aid,bid,num')->select()->toArray();
                    $products = Db::name('collage_product')->where('1=1')->field('aid,bid,sales')->select()->toArray();
                    break;
                case 'kanjia':
                    $orders = Db::name('kanjia_order')->whereIn('status',[1,2,3])->field('aid,bid,num')->select()->toArray();
                    $products = Db::name('kanjia_product')->where('1=1')->field('aid,bid,sales')->select()->toArray();
                    break;
                case 'seckill':
                    $orders = Db::name('seckill_order')->whereIn('status',[1,2,3])->field('aid,bid,num')->select()->toArray();
                    $products = Db::name('seckill_product')->where('1=1')->field('aid,bid,sales')->select()->toArray();
                    break;
                case 'tuangou':
                    $orders = Db::name('tuangou_order')->whereIn('status',[1,2,3])->field('aid,bid,num')->select()->toArray();
                    $field = 'aid,bid,sales';
                    if(getcustom('yx_tuangou_vrnum')){
                        $field = 'aid,bid,(sales+vrnum) sales';
                    }
                    $products = Db::name('tuangou_product')->where('1=1')->field($field)->select()->toArray();
                    break;
                case 'scoreshop':
                    $orders = Db::name('scoreshop_order_goods')->whereIn('status',[1,2,3])->field('aid,bid,num')->select()->toArray();
                    $products = Db::name('scoreshop_product')->where('1=1')->field('aid,bid,sales')->select()->toArray();
                    break;
                case 'lucky_collage':
                    $orders = Db::name('lucky_collage_order')->whereIn('status',[1,2,3])->field('aid,bid,num')->select()->toArray();
                    $products = Db::name('lucky_collage_product')->where('1=1')->field('aid,bid,sales')->select()->toArray();
                    break;
                case 'yuyue':
                    $orders = Db::name('yuyue_order')->whereIn('status',[1,2,3])->field('aid,bid,num')->select()->toArray();
                    $products = Db::name('yuyue_product')->where('1=1')->field('aid,bid,sales')->select()->toArray();
                    break;
                case 'kecheng':
                    $orders = Db::name('kecheng_order')->whereIn('status',[1,2,3])->field('aid,bid')->select()->toArray();
                    $products = Db::name('kecheng_list')->where('1=1')->field('aid,bid')->select()->toArray();
                    break;
                case 'cycle':
                    $orders = Db::name('cycle_order')->whereIn('status',[1,2,3])->field('aid,bid,num')->select()->toArray();
                    $products = Db::name('cycle_product')->where('1=1')->field('aid,bid,sales')->select()->toArray();
                    break;
                case 'restaurant_takeaway':
                    $orders = Db::name('restaurant_takeaway_order_goods')->whereIn('status',[1,2,3])->field('aid,bid,num')->select()->toArray();
                    $products = Db::name('restaurant_product')->where('1=1')->field('aid,bid,sales')->select()->toArray();
                    break;
                case 'restaurant_shop':
                    $orders = Db::name('restaurant_shop_order_goods')->whereIn('status',[1,2,3])->field('aid,bid,num')->select()->toArray();
                    break;
            }


            //更新商户虚拟销量
            foreach($products as $product){
                if($product && empty($product['sales'])){
                    $product['sales'] = 0;
                }
                $aid = $product['aid']?:1;
                $bid = $product['bid'];
                $business = Db::name('business')->where('id',$bid)->find();
                if($bid && !$business){
                    continue;
                }
                $sale_num = $product['sales'];
                $business_sales = Db::name('business_sales')
                    ->where('aid',$aid)
                    ->where('bid',$bid)
                    ->find();

                if(!$business_sales && $sale_num>0){
                    $data_sales = [];
                    $data_sales['aid'] = $aid;
                    $data_sales['bid'] = $bid;
                    $data_sales['sales'] = $sale_num;
                    $data_sales['total_sales'] = $sale_num;
                    Db::name('business_sales')->insert($data_sales);
                }else{
                    $data_sales = [];
                    $data_sales['sales'] = $business_sales['sales']+$sale_num;
                    $data_sales['total_sales'] = $business_sales['total_sales']+$sale_num;
                    Db::name('business_sales')->where('id',$business_sales['id'])->update($data_sales);
                }
            }

            //更新商户订单销量
            foreach($orders as $order){
                if($order && empty($order['num'])){
                    $order['num'] = 1;
                }
                $aid = $order['aid']?:1;
                $bid = $order['bid'];
                $business = Db::name('business')->where('id',$bid)->find();
                if($bid && !$business){
                    continue;
                }
                $sale_num = $order['num'];
                $sales_field = $sales_type[$type];
                $business_sales = Db::name('business_sales')
                    ->where('aid',$aid)
                    ->where('bid',$bid)
                    ->find();

                if(!$business_sales && $sale_num>0){
                    $data_sales = [];
                    $data_sales['aid'] = $aid;
                    $data_sales['bid'] = $bid;
                    $data_sales[$sales_field] = $sale_num;
                    $data_sales['total_sales'] = $sale_num;
                    Db::name('business_sales')->insert($data_sales);
                }else{
                    $data_sales = [];
                    $data_sales[$sales_field] = $business_sales[$sales_field]+$sale_num;
                    $data_sales['total_sales'] = $business_sales['total_sales']+$sale_num;
                    Db::name('business_sales')->where('id',$business_sales['id'])->update($data_sales);
                }
            }
        }
        Db::commit();

        die('更新完成');

    }

    //奖金池
    public function bonusPoolDaily(){
        if(getcustom('product_bonus_pool')){
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset) {
                $yesterday_start = strtotime(date('Y-m-d 00:00:00', strtotime('-1 day')));
                $yesterday_end = strtotime(date('Y-m-d 23:59:59', strtotime('-1 day')));
                $order = Db::name('shop_order')->where('paytime','between',[$yesterday_start,$yesterday_end])->where('status','in',[1])->where('aid',$sysset['aid'])->find();
                $poolshopset = Db::name('shop_sysset')->where('aid',$sysset['aid'])->field('bonus_pool_money_max,bonus_pool_cx_days,bonus_pool_already,bonus_pool_noreleasetj')->find();
                
                //如果昨天没有业绩，进行释放
                if(!$order){
                    //连续释放次数 小于 设置的次数才能进行释放
                    
                    if($poolshopset['bonus_pool_already'] >= $poolshopset['bonus_pool_cx_days']){
                        continue;
                    }
                    //发放奖励
                    $release_list = Db::name('shop_order')->alias('so')
                        ->join('member m','m.id = so.mid')
                        ->where('so.status','in',[1,2,3])
                        ->where('so.aid',$sysset['aid'])
                        ->order('so.paytime asc')
                        ->field('so.id,so.aid,so.status,so.createtime,so.mid,m.bonus_pool_money,m.levelid')
                        ->group('so.mid')
                        ->select()->toArray(); 
                  
                    //释放奖金池
                    if($release_list){
                        foreach ($release_list as $mk=>$mv){
                            $pool = Db::name('bonus_pool')->where('aid',$mv['aid'])->where('status',0)->order('id asc')->find();
                            
                            if(!$pool){
                                continue;
                            }
                            //用户达到上限，不释放
                            if($mv['bonus_pool_money']+$pool['money'] >= $poolshopset['bonus_pool_money_max']){
                                \think\facade\Log::write($mv['mid'].'达到上限');
                                continue;
                            }
                            $bonus_pool_money = dd_money_format($mv['bonus_pool_money'] + $pool['money']);
                            //增加log
                            $log = [
                                'aid' =>$mv['aid'],
                                'mid' =>$mv['mid'],
                                'frommid' => 0,
                                'commission' => $pool['money'],
                                'after' => $bonus_pool_money,
                                'createtime' => time(),
                                'remark' => '奖金发放'
                            ];
                            Db::name('member_bonus_pool_log') ->insert($log);
                            //修改奖金池状态
                            Db::name('member')->where('id',$mv['mid'])->update(['bonus_pool_money' => $bonus_pool_money]);
                            Db::name('bonus_pool')->where('aid',$mv['aid'])->where('id',$pool['id'])->update(['status' => 1,'mid' => $mv['mid'],'endtime' => time()]);
                        }
                        //持续每天的次数增加1
                        Db::name('shop_sysset')->where('aid',$sysset['aid'])->inc('bonus_pool_already',1)->update();
                    }
                }else{
                    //有订单 持续每天 设置为0 从头开始
                    Db::name('shop_sysset')->where('aid',$sysset['aid'])->update(['bonus_pool_already' => 0]);
                }
            }
        }
       
    }
    //线下优惠券
    public function xianixaCouponYeji(){
        if(getcustom('coupon_xianxia_buy')){
            $month_last = date( "Y-m-t");
            $now_date = date('Y-m-d');
            //判断当前天 是不是当月最后一天 
            if($month_last !=$now_date){
                return;
            }
            $month_start = strtotime(date('Y-m-01 00:00:00'));
            $month_end=strtotime(date('Y-m-t 23:59:59')); 
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset) {
                $levellist = Db::name('member_level')->where('aid',$sysset['aid'])->select()->toArray();
                
                foreach ($levellist as $level){
                    //如果不设置业绩，不进行操作
                    if(!$level['yeji_reward_data']){
                         continue;
                    }
                    $yeji_reward_data = json_decode($level['yeji_reward_data'],true);
                   
                    $memberlist = Db::name('member')->where('aid',$sysset['aid'])->where('levelid',$level['id'])->select()->toArray();
                    foreach($memberlist as $member){
                      $res = \app\common\Member::xianxiaYeji($sysset['aid'],$member,$yeji_reward_data,$month_start,$month_end);
                        if($res['commission'] > 0){
                            \app\common\Member::addcommission($sysset['aid'], $member['id'],  $member['id'], $res['commission'], '业绩奖');
                        }
                    }
                }
            }
        }
    }
    //平台加权奖励【每月1号发放】
    public function platformAvgBonus($type=0){
        if(getcustom('commission_platform_avg_bonus')){
            $day = intval(date('d'));
            if($day!=1 && $type==0){
                return;
            }
            $monthEnd = strtotime(date('Y-m-01 00:00:00',time()));
            $month = date('m',$monthEnd-86400*2);
            //等级下面设置平台奖励的会员
            $mwhere = [];
            $mwhere[] = ['m.levelid','>',0];
            $mwhere[] = ['l.isdefault','=',0];
            $mwhere[] = ['l.platform_avgbonus_percent','>',0];
            $list = Db::name('member')->alias('m')->join('member_level l','m.levelid=l.id')->where($mwhere)->field('m.aid,m.id,m.levelid,l.platform_avgbonus_percent')->select()->toArray();
            //按平台分组
            $data = [];//有要发放的记录 按aid发放
            foreach ($list as $k=>$v){
                $data[$v['aid']][] = $v;
            }
            foreach ($data as $aid=>$members){
                //平台总业绩
//                $orderMoneyCount = 0 + Db::name('shop_order')->where('aid',$aid)->where('status',3)->sum('totalprice');
                $sumResult = Db::name('shop_order')->where('aid',$aid)->where('status',3)->field("sum(`totalprice`-`refund_money`) as totalamount")->find();
                $orderMoneyCount = $sumResult['totalamount'];
                //奖励多少
                foreach ($members as $k=>$member){
                    $bonusPercent = $member['platform_avgbonus_percent'];
                    //同等级的会员平均佣金
                    $levelCount = Db::name('member')->where('aid',$aid)->where('levelid',$member['levelid'])->count('id');
                    $commission = $orderMoneyCount * $bonusPercent * 0.01 / $levelCount;//平均值
                    if($commission){
                        \app\common\Member::addcommission($aid,$member['id'],0,$commission,$month.'月份等级业绩达标平台奖励');
                        Db::name('member_commission_record')->insert(['aid'=>$aid,'mid'=>$member['id'],'type'=>'platform','commission'=>$commission,'score'=>0,'remark'=>$month.'月份等级业绩达标平台奖励','createtime'=>time(),'endtime'=>time(),'status'=>1]);
                    }
                }
            }
        }
    }
    //薪资奖励【每月1号发放】type=0脚本执行
    public function levelSalaryBonus($type=0){
        if(getcustom('member_level_salary_bonus')){
            //每个月1号结算
            $day = intval(date('d'));
            if($day!=1 && $type==0){
                return;
            }
            //上个月的业绩
            $monthEnd = strtotime(date('Y-m-01 00:00:00',time()));
            $days = date('t',$monthEnd-86400*2);//上个月多少天
            $month = date('m',$monthEnd-86400*2);
            $monthStart = $monthEnd - 86400*$days;
            //等级下面设置平台奖励的会员
            $mwhere = [];
            $mwhere[] = ['m.levelid','>',0];
            $mwhere[] = ['l.isdefault','=',0];
            $mwhere[] = ['l.salary_bonus_content','<>',''];
            $mwhere[] = Db::raw('l.salary_bonus_content IS NOT NULL');
            $members = Db::name('member')->alias('m')->join('member_level l','m.levelid=l.id')->where($mwhere)->field('m.aid,m.id,m.levelid,l.salary_bonus_content')->select()->toArray();
            foreach ($members as $k=>$member){
                $aid = $member['aid'];
                //直推会员
                $yejiAmount = \app\model\Commission::getMiniTeamCommission($aid,$member['mid'],$monthStart,$monthEnd);
                if($yejiAmount<=0){
                    continue;
                }
                $memberNum = Db::name('member')->where('aid', $aid)->where('pid', $member['mid'])->count('id');
                $bonuslist = json_decode($member['salary_bonus_content'],true);
                //倒叙找符合的第一个
                $newbonuslist = array_reverse($bonuslist);
                foreach ($newbonuslist as $bk=>$bonus){
                    if($memberNum>=$bonus['member_num'] && $yejiAmount>=$bonus['yj_amount'] && $bonus['bonus']>0){
                        //发放达标奖励
                        $commission = $bonus['bonus'];
                        \app\common\Member::addcommission($aid,$member['id'],0,$commission,$month.'月份业绩达标工资补贴');
                        Db::name('member_commission_record')->insert(['aid'=>$aid,'mid'=>$member['id'],'type'=>'salary','commission'=>$commission,'score'=>0,'remark'=>$month.'月份业绩达标工资补贴','createtime'=>time(),'endtime'=>time(),'status'=>1]);
                        break;
                    }
                }
            }
        }
    }

    //佣金自动转积分，每日0点执行一次
    public function commission_to_score(){
        if(getcustom('commission_to_score')){
            Db::startTrans();
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset){
                //查询今日是否有转换记录
                $today = date('Ymd',time());
                $exit = Db::name('commission_toscore_log')->where('aid',$sysset['aid'])->where('w_day',$today)->find();
                if($exit){
                    continue;
                }
                if($sysset['commission_to_score_time']==1){
                    //设置手动发放的跳过
                    continue;
                }
                $res = \app\common\Member::commission_to_score($sysset);
                dump($res);
            }
            Db::commit();
        }
        dump('完成');
    }

    public function day_give(){
        if(getcustom('yx_day_give')){
            //每日赠送
            Db::startTrans();
            $aids = Db::name('admin')->where('status',1)->column('id');
//        $aids = [6];
            if(empty($aids)) return;
            $setlist = Db::name('day_give')->whereIn('aid',$aids)->where('status',1)->select()->toArray();
            foreach($setlist as $set){
                //查询今日是否有记录
                $today = date('Y-m-d');
                $yesterdaytime = strtotime($today);
                $exit = Db::name('day_give_log')->where('aid',$set['aid'])->where('date',$today)->find();
                if($exit){
                    \think\facade\Log::write([
                        'file'=>__FILE__,
                        'fun'=>__FUNCTION__,
                        'line'=>__LINE__,
                        'msg'=>'今日分红数据已存在'
                    ]);
                    continue;
                }
                $config = json_decode($set['config_data'],true);
                if(empty($config)) continue;
                $levelids = array_keys($config);
                $memberList = Db::name('member')
                    ->field('id,aid,pid,path,levelid,createtime,day_give_score_total,day_give_commission_total')
                    ->where('aid',$set['aid'])->whereIn('levelid',$levelids)->where('createtime','<',$yesterdaytime)->select()->toArray();
                foreach ($memberList as $item) {
                    $configLevel = $config[$item['levelid']];
                    //上限
                    if(($item['day_give_score_total'] >= $configLevel['scoreMax'] && $configLevel['scoreMax'] > 0) && ($item['day_give_commission_total'] >= $configLevel['commissionMax'] && $configLevel['commissionMax'] > 0)){
                        \think\facade\Log::write([
                            'file'=>__FILE__,
                            'fun'=>__FUNCTION__,
                            'line'=>__LINE__,
                            'member'=>$item,
                            'msg'=>'已达上限'
                        ]);
                        continue;
                    }
                    //查询昨日之前注册的下级
                    $whereM = [];
                    $whereM[] = ['aid', '=', $set['aid']];
                    $whereM[] = ['createtime','<',$yesterdaytime];
                    $levelidsChild = explode(',',$set['gettj_children']);
                    if(!in_array('-1',$levelidsChild)){
                        $whereM[] = ['levelid','in',$levelidsChild];
                    }
                    if(empty($levelidsChild)){
                        \think\facade\Log::write([
                            'file'=>__FILE__,
                            'fun'=>__FUNCTION__,
                            'line'=>__LINE__,
                            'levelidsChild'=>$levelidsChild,
                            'msg'=>'下级条件为空'
                        ]);
                        continue;
                    }
                    $children1 = Db::name('member')->where($whereM)->where('pid',$item['id'])->column('id');
                    $children2 = [];
                    $children3 = [];
                    if($children1){
                        $children2 = Db::name('member')->where($whereM)->whereIn('pid',$children1)->column('id');
                        if($children2){
                            $children3 = Db::name('member')->where($whereM)->whereIn('pid',$children2)->column('id');
                        }
                    }
                    $score = 0;
                    //scoreMax 0或空无上限
                    if($item['day_give_score_total'] < $configLevel['scoreMax'] || empty($configLevel['scoreMax'])){
                        $score = $configLevel['score'];
                        if($children1) $score += $configLevel['score1'] * count($children1);
                        if($children2) $score += $configLevel['score2'] * count($children2);
                        if($children3) $score += $configLevel['score3'] * count($children3);
                        if($configLevel['scoreMax'] > 0 && $score + $item['day_give_score_total'] > $configLevel['scoreMax']){
                            $score = $configLevel['scoreMax'] - $item['day_give_score_total'];
                        }
                    }
                    $commission = 0;
                    if($item['day_give_commission_total'] < $configLevel['commissionMax'] || empty($configLevel['commissionMax'])){
                        $commission = $configLevel['commission'];
                        if($children1) $commission += $configLevel['commission1'] * count($children1);
                        if($children2) $commission += $configLevel['commission2'] * count($children2);
                        if($children3) $commission += $configLevel['commission3'] * count($children3);
                        if($configLevel['commissionMax'] > 0 && $commission + $item['day_give_commission_total'] > $configLevel['commissionMax']){
                            $commission = $configLevel['commissionMax'] - $item['day_give_commission_total'];
                        }
                    }
                    if($score > 0){
                        \app\common\Member::addscore($item['aid'],$item['id'],$score,'系统每日奖励');
                        Db::name('member')->where('aid',$set['aid'])->where('id',$item['id'])->inc('day_give_score_total',$score)->update();
                    }
                    if($commission > 0){
                        \app\common\Member::addcommission($item['aid'],$item['id'],0,$commission,'系统每日奖励');
                        Db::name('member')->where('aid',$set['aid'])->where('id',$item['id'])->inc('day_give_commission_total',$commission)->update();
                    }
                    if($score > 0 || $commission > 0)
                        Db::name('day_give_log')->insert(['aid'=>$item['aid'],'mid'=>$item['id'],'date'=>$today,'score'=>$score,'commission'=>$commission,'createtime'=>time()]);
                }
            }
            Db::commit();
        }
    }
    
    //团队分红奖励
    public function teamyejiJiangli(){
        if(getcustom('yx_team_yeji')){
            //->where('1=1')
            $syssetlist = Db::name('admin_set')->where('aid',1)->select()->toArray();
            foreach($syssetlist as $sysset) {
                $yeji_set = Db::name('team_yeji_set')->where('aid',$sysset['aid'])->find();
                if($yeji_set['status'] ==0){//未开启
                    \think\facade\Log::write($sysset['aid'].'团队业绩分红功能关闭');
                    continue;
                }
                if($yeji_set['jiesuan_type'] ==1){//按月
                    if(date('d') !='01' ||  date('H') !='01'){
                        continue;
                    }
                }
                if($yeji_set['jiesuan_type'] ==2){//按年
                    if(date('m-d') !='01-01' ||  date('H') !='01'){
                        echo 222;
                        continue;
                    }
                }
                
                $config = json_decode($yeji_set['config_data'],true);
                $member_list = Db::name('member')->where('aid',$sysset['aid'])->limit(0,10)->where('path','<>','')->order('id desc')->select()->toArray();
                foreach($member_list as $key=>$member){
                    $mid = $member['id'];
                    $now_month = date('Y-m',strtotime('-1 month'));
                    $xuni_yeji = 0;  //虚拟业绩
                    $yejiwhere = [];
                    if($yeji_set['jiesuan_type'] ==1){//按月
                        $month_start = strtotime(date('Y-m-01 00:00:00',strtotime('-1 month')));
                        $month_end  = strtotime(date('Y-m-t 23:59:59',strtotime('-1 month')));
                        $yejiwhere[] = ['createtime','between',[$month_start,$month_end]];
                        //虚拟业绩
                        $xuni_yeji = 0 +Db::name('tem_yeji_xuni')->where('aid',$sysset['aid'])->where('mid',$mid)->where('yeji_month',$now_month)->value('yeji');
                    }
                    if($yeji_set['jiesuan_type'] ==2){//按年
                        $year_start=strtotime((date('Y')-1) . '-01-01 00:00:00');
                        $year_end=strtotime((date('Y')-1) . '-12-31 23:59:59');
                        $yejiwhere[] = ['createtime','between',[$year_start,$year_end]];
                    }

                    $yejiwhere[] = ['status','in','1,2,3'];
                    $downmids = \app\common\Member::getteammids($sysset['aid'],$mid);
                    
                    if(!$downmids){
                        \think\facade\Log::write($member['id'].'团队为空');
                        continue;
                    }
                    //下级人数
                    $teamyeji = Db::name('shop_order_goods')->where('aid',$sysset['aid'])->where('mid','in',$downmids)->where($yejiwhere)->sum('totalprice');//real_totalprice totalprice 
                    $totalyeji =$teamyeji +  $xuni_yeji;
                    //阶梯设置
                    $jt_range = $config[$member['levelid']]['range'];
                    if(!$jt_range){
                        \think\facade\Log::write($member['id'].'_'.$member['levelid'].'无设置');
                        continue;
                    }
                 
                    $ratio = 0;
                    foreach($jt_range as $rk=>$range){
                        if( $range['start'] <= $totalyeji && $totalyeji < $range['end']){
                            $ratio = $range['ratio'];
                        }
                    }
                    $fenhong = 0;
                    if($ratio > 0){
                        $fenhong = $ratio /100 * $totalyeji; 
                    }
                    if($fenhong > 0){
                        
                        \app\common\Member::addcommission($sysset['aid'],$mid,0,$fenhong,'团队业绩分红',1,'teamfenhong');
                    }
                }
            }
        }
    }

    //店铺分销
    public function businessfenxiao(){
        if(getcustom('business_fenxiao')){
            //->where('1=1')
            Db::startTrans();
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset) {
                \app\common\Business::business_fenxiao($sysset,0);
            }
            Db::commit();
        }
    }
    //分销补贴发放
    public function commission_butie(){
        if(getcustom('commission_butie')){
            //->where('1=1')
            Db::startTrans();
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset) {
                \app\common\Member::commission_butie($sysset['aid']);
            }
            Db::commit();
            die('stop');
        }
    }

    //统计计算累计积分
    public function count_totalscore(){
    	$admins = Db::name('admin')->where('status',1)->field('id')->select()->toArray();
    	if($admins){
    		foreach($admins as $admin){
    			$aid = $admin['id'];
    			//查询未统计的累计积分的会员
    			$members = Db::name('member')->where('aid',$aid)->where('iscountscore',0)->where('totalscore',0)->field('id,totalscore')->select()->toArray();
    			if($members){
    				foreach($members as $member){
    					//统计计算下他累计积分
            			$totalscore = 0+Db::name('member_scorelog')->where('mid',$member['id'])->where('score','>',0)->where('aid',$aid)->sum('score');
            			//再次验证是否统计过
            			$count = 0+Db::name('member')->where('id',$member['id'])->where('iscountscore',1)->count('id');
            			if(!$count){
            				Db::name('member')->where('id',$member['id'])->update(['totalscore'=>$totalscore,'iscountscore'=>1]);
            			}
    				}
    			}
    		}
    	}
    }

    //释放通证
    public function release_tongzheng(){
        if(getcustom('product_givetongzheng')){
            //->where('1=1')
            Db::startTrans();
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset) {
                \app\common\Member::release_tongzheng($sysset);
            }
            Db::commit();
            die('stop');
        }
    }

    //满人抽奖活动开奖
    public function manren_choujiang(){
        if(getcustom('yx_choujiang_manren')){
            Db::startTrans();
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset) {
                \app\common\Choujiang::kaijiang($sysset);
            }
            Db::commit();
        }
    }
}